【问题标题】:how to read attribute value in json using android如何使用android读取json中的属性值
【发布时间】:2011-03-29 07:09:18
【问题描述】:

我要读取json属性值,我的json格式是这样的

{"content":{"@attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},

我想从 json 属性中读取 total_record 的值。我该如何阅读?请帮帮我

谢谢 约翰·瑞克

【问题讨论】:

    标签: android json


    【解决方案1】:

    首先检查您的 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;
    }
    

    希望你能理解问题。

    【讨论】:

    • 应该被接受为正确答案!谢谢,也在找这个:)
    【解决方案2】:

    只需使用JSONObject

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

    不是 100% 确定它有效,但它是一个很好的例子。

    【讨论】:

    • @谢谢你的回复,你能举一些例子从json的total_records中获取价值
    • 您的代码假定 total_records 是顶级对象的属性,但事实并非如此。
    • @RoToRa,我没有写,这是一个解决方案。只是指出了方向。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多