将数字值与文本值分开 [英] Separating Numeric values from Text Values
问题描述
我正在从 REST API 检索信息并显示:
I am retrieving information from a REST API and it displays:
"Per 78g - Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"
我已将这些项目导入到 ListView 中,当用户单击一个项目时,我想将每个数值单独串起来,如下所示,没有它们的文本.基于上面的例子:
I have imported the items into a ListView and when a user clicks an item I would like to string each numeric value individually like below without their text. Based on the example above:
String calories = 221;
String fat = 12.65;
String carbs = 16.20;
String protein = 10.88;
我摆脱了每 78 克":
I got rid of the "Per 78g" with:
String sd = food.getString("food_description");
String[] row = sd.split("-");
tems.add(new Item(food.getString("food_name"), row[1]));
在每个列表项中显示以下内容.
Which displays the following in each list item.
"Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"
当用户单击列表项时:我如何正确地将其分开并同时消除文本?一旦我单独获得数值,我会没事的.
When the User clicks on a list Item: How do I separate this properly and eliminate the text as well? Once I get the numeric values individually I would be fine.
@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 的示例:
The API documentation is really bad and outdated. I am using it because it has great information. For everyone that believes this is bad practice this is the example return 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,将使您的工作更轻松:
Changing your JSON as follows, will make your job more easier:
{
"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().
I am assuming you know how to parse it.
And in case you are not able to change your json, try to use StringTokenizer or use String.split().
这篇关于将数字值与文本值分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!