首页 > 解决方案 > 遍历 JSON 中收到的对象列表

问题描述

我有以下 JSON 数据:

[
  {
    "id": 4,
    "siteName": "site1",
    "addressLine1": "address1",
    "addressLine2": "address2",
    "town": "town1",
    "postcode": "postcode1",
    "contactName": "name1",
    "contactNumber": "number1",
    "contactEmail": "email1"
  },
  {
    "id": 5,
    "siteName": "site2",
    "addressLine1": "address1",
    "addressLine2": "address2",
    "town": "town1",
    "postcode": "postcode1",
    "contactName": "name1",
    "contactNumber": "number1",
    "contactEmail": "email1"
  },
]

我正在解析数据,但它只是输出一个长字符串。我想访问每个对象中的每个元素。

更新:我正在输出单个元素,但由于某种原因,“id”属性被认为是双精度的?

Map<String,Object> jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));

java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)jsonArr.get("root");

 for(Map<String, Object> obj : content) {

                                Log.p((int)obj.get("id"));
                                Log.p((String)obj.get("siteName"));
                                Log.p((String)obj.get("addressLine1"));
                                Log.p((String)obj.get("addressLine2"));
                                Log.p((String)obj.get("town"));
                                Log.p((String)obj.get("postcode"));
                                Log.p((String)obj.get("contactName"));
                                Log.p((String)obj.get("contactNumber"));
                                Log.p((String)obj.get("contactEmail"));
                            }

标签: javacodenameone

解决方案


当您使用 Codename One 时,parseJSON 始终返回 a Map<String, Object>,但当根元素是数组时表现不同。在这种情况下,返回Map的对象包含一个对象,其键是"root"您然后可以迭代以获取实际对象。

Map<String, Object> data = json.parseJSON(new InputStreamReader(
    new ByteArrayInputStream(r.getResponseData()), "UTF-8"));

List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");

for(Map<String, Object> obj : content) {
    Log.p(obj.getValue().toString());
}

有关详细信息,请参阅该方法的文档parseJSON


推荐阅读