繁体   English   中英

如何使用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"}]}}

在其中,您在“项目”之前留了一个右花括号。

现在下面是获取“ 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;
}

希望您理解问题。

只需使用JSONObject

JSONObject obj = new JSONObject(src);
String totalRecs = obj.getString("total_records");

并非100%确信它可以正常工作,但这是一个很好的起点示例。

希望您在尝试提出要求之前已经尝试过。 如果没有,这是一些网址(我用Google搜索过): http : //www.androidcompetencycenter.com/2009/10/json-parsing-in-android/http://about-android.blogspot.com/2010 /03/androind-json-parser.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM