【问题标题】:Parse simple JSON Array解析简单的 JSON 数组
【发布时间】:2014-02-23 10:03:49
【问题描述】:

我正在尝试解析这个相对简单的 JSON 数组:

{
   "tags":[
      "Cheese",
      "Milk",
      "Yoghurt"
   ],
   "success":1,
   "message":"Tags found"
}

我得到的是这样的:

        Log.d("Tag products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt("success");

            if (success == 1) {
                // products found
                // Getting Array of Products
                JSONArray products = json.getJSONArray("tags");

            } else {
                // no products found
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

我的数组完美地记录到我的 logcat 中。我成功地检索了成功和消息的价值。但我无法解析实际的标签。

大多数关于 json 解析的示例和教程都使用了另一种格式,所以我也会非常高兴有一个示例来演示这种数组的解析。

【问题讨论】:

    标签: android arrays json parsing


    【解决方案1】:

    遍历json数组,根据索引获取item。

    解析

    JSONArray products = json.getJSONArray("tags");
    for(int i=0;i<products.length();i++)
    {
    String value= (String) products.get(i);
    Log.i(".........",value);
    }
    

    你也可以看@gson

    https://code.google.com/p/google-gson/

    【讨论】:

      【解决方案2】:

      您共享的json对象可以建模为以下Model类:

       public class ModelClass
          {
              public List<string> tags { get; set; }
              public int success { get; set; }
              public string message { get; set; }
          }
      

      一旦您将 json 字符串解析为 ModelClass 的对象,您就可以访问标签列表并获取其中的值。

      您可以使用 gson 解析器进行反序列化。

      Gson gsonParser = new Gson();
      ModelClass modelObject = new ModelClass();
      modelObject = gsonParser.fromJson(jsonString, modelObject.getClass());
      
      for(String tagString : modelObject.tags)
      {
         Log.d("AppTag", tagString);
      }
      

      【讨论】:

      • 感谢您的回答,尽管我更喜欢 Raghunandan 的回答,因为它更紧凑(代码)
      猜你喜欢
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      相关资源
      最近更新 更多