我正在尝试用以下方法解析我的 json:
for(int i = 0; i < json.getJSONArray("JSON").length(); i++) {
String taste = json.getJSONArray("JSON").getJSONObject(i).getString("taste");
String rate = json.getJSONArray("JSON").getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}
但是最后我的日志根本没有输出任何东西,所以我假设我没有正确解析我的 json。我正在查看的 json 是:
[{"taste":"Bitter","rate":"13"},{"taste":"Malty","rate":"3"},{"taste":"Smooth","rate":"3"},{"taste":"Dry","rate":"1"}]
我想我可能错了:
json.getJSONArray("JSON")
因为我的数组没有名称,但我必须使用字符串...
最佳答案
我在您的 JSON 字符串中没有找到“JSON”。所以我认为您应该这样写:
JSONArray jsonArray = new JSONArray(json);
然后:
for(int i = 0; i < jsonArray.length(); i++) {
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}
关于android - 没有从android中的json获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332782/