如何使用Android读取JSON中的属性值 [英] how to read attribute value in json using android
问题描述
我想读取json属性值,我的json格式是这样
{"content":{"@attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},
我想从json属性读取total_record的值.我该如何阅读?请帮助我
谢谢 约翰·里克
首先检查您的JSON字符串.将其更改为
的 {"content":{"@attributes" : { "start_limit" :"x","end_limit" : "x","total_records" : "x"}},"item":[{"category":"x","distance':"x"}]}}
{"content":{"@attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}}
您在其中的"item"之前留了一个右花括号.
下面是获取"total_records"值的代码
String jsonString = "{'content':{'@attributes' : { 'start_limit' :'x','end_limit' : 'x','total_records' : 'x'}},'item':[{'category':'x','distance':'x'}]}}";
public String getTotalRecords(String jsonString){
try {
JSONObject mainObject = new JSONObject(jsonString);
JSONObject contentObject = mainObject.getJSONObject("content");
JSONObject attributesObject = contentObject.getJSONObject("@attributes");
String totalRecords = attributesObject.getString("total_records");
Log.i("Total Records", totalRecords);
} catch (JSONException e) {
e.printStackTrace();
}
return totalRecords;
}
希望您能理解问题.
I want to read json attribute value, my json format like this
{"content":{"@attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},
I want to read total_record's value from json attributes. How can I read ? Please help me
Thanks John Rick
First of all check your JSON String.Change it to
{"content":{"@attributes" : { "start_limit" :"x","end_limit" : "x","total_records" : "x"}},"item":[{"category":"x","distance':"x"}]}}
from
{"content":{"@attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}}
In which you left one closing curly brace before "item".
Now below is the code to get value of "total_records"
String jsonString = "{'content':{'@attributes' : { 'start_limit' :'x','end_limit' : 'x','total_records' : 'x'}},'item':[{'category':'x','distance':'x'}]}}";
public String getTotalRecords(String jsonString){
try {
JSONObject mainObject = new JSONObject(jsonString);
JSONObject contentObject = mainObject.getJSONObject("content");
JSONObject attributesObject = contentObject.getJSONObject("@attributes");
String totalRecords = attributesObject.getString("total_records");
Log.i("Total Records", totalRecords);
} catch (JSONException e) {
e.printStackTrace();
}
return totalRecords;
}
Hope you understand the problem.
这篇关于如何使用Android读取JSON中的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!