0

我正在从 REST API 检索信息,它显示:

"Per 78g - Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

我已将这些项目导入 ListView,当用户单击一个项目时,我想单独将每个数值串起来,如下所示,没有它们的文本。基于上面的例子:

String calories = 221;
String fat = 12.65;
String carbs = 16.20;
String protein = 10.88;

我摆脱了“每78克”:

String sd = food.getString("food_description");
String[] row = sd.split("-");
tems.add(new Item(food.getString("food_name"), row[1]));

在每个列表项中显示以下内容。

"Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

当用户单击列表项时:如何正确分隔并消除文本?一旦我单独获得数值,我就可以了。

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

    String calories = adapter.getItem(arg2).getDescription();

    String[] calRow = calories.split("?|?");

    Toast.makeText(getActivity(), "" + calRow[1], Toast.LENGTH_LONG).show();

    mCallback.onFoodSelected(adapter.getItem(arg2).getTitle(), calRow[1]);
}

API 文档真的很糟糕而且过时了。我正在使用它,因为它包含大量信息。对于认为这是不好的做法的每个人,这是返回 JSON 的示例:

{  
   "foods":{  
      "food":{  
         "food_description":"Per 342g - Calories: 835kcal | Fat: 32.28g | Carbs: 105.43g | Protein: 29.41g",
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}
4

1 回答 1

1

如下更改您的 JSON,将使您的工作更轻松:

{  
   "foods":{  
      "food":{  
         "food_description":{
            "Per" : "342g",
            "Calories": "835kcal",
            " Fat": "32.28g",
            "Carbs":" 105.43g",
            " Protein": "29.41g"
            },
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}

我假设你知道如何解析它。
如果您无法更改 json,请尝试使用StringTokenizer或使用 String.split()。

于 2014-10-24T06:00:27.237 回答