0

我有一个如下所示的 JSON:

{
        "places": [{
            "name": "Ankola",
            "slug": "ankola",
            "category": "beach",
            "distance": "521",
            "travel_time": "8 hrs, 2 mins",
            "days": "3",
            "latitude": "14.669456",
            "longitude": "74.300952",
            "weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
            "todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
            "about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
           "image": [
                     "Cm5NXlq.jpg",
                     "9OrlQ9C.jpg",
                     "DRWZakh.jpg",
                     "dFKVgXA.jpg",
                     "5WO2nDf.jpg"
                     ]

        }]
}

我知道如何获取键值对,但我不知道如何解析 json 中的数组以形成字符串数组(图像 - 在我的情况下)

总而言之,我想要这样的东西:我在“图像”标签下有 5 个图像名称,我希望它们在一个字符串数组中。我怎样才能做到这一点?

4

4 回答 4

1

采用 :

JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
   String image = images.getString(i);
}

我记得这应该可以解决问题。

于 2013-02-14T10:05:29.593 回答
1

干得好:

JSONArray ja = whatEverYourJsonObject.getJSONArray("image");

for(int i=0; i<ja.length(); j++){
    String name = ja.getString(i);
}
于 2013-02-14T10:08:28.820 回答
1

您首先必须将 JSON 字符串转换为 Java 对象 ( JSONObject)。然后,您获得JSONArray并迭代它。

例子:

JSONObject jsonObj = null;
try {
    jsonObj = new JSONObject (jsonString);
    JSONArray images = itemObj.getJSONArray ("images");
    int length = images.length ();

    for (int i = 0; i < length; i++)
        Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
    e.printStackTrace();
}

编辑:现在我看到您的 JSON 无效 - 每个图像都有一个对象,并且该对象仅包含数据的值部分。有效图像数组的示例如下:

{
    "image": [
        "Cm5NXlq.jpg",
        "9OrlQ9C.jpg",
        "DRWZakh.jpg",
        "dFKVgXA.jpg",
        "5WO2nDf.jpg"
    ]
}
于 2013-02-14T10:11:18.583 回答
1

我会建议:

  1. 创建您自己的类,该类描述由这些 json 对象定义的数据结构。作为最后的手段,您甚至可以基于 JSON 字符串生成 Java 类 - 查看 jsongen
  2. 当您拥有自己的 Java 类(比如说)时,您可以使用GSONMyClass轻松地将 JSON 解析为生成的 Java 类,例如:

    MyClass myClass = gson.fromJson(jsonString, MyClass.class);

于 2013-02-14T10:21:40.660 回答