如何在地图中存储JsonArray?

时间:2015-07-01 06:02:19

标签: java json

我使用了以下代码

JSONArray jsonArray = new  JSONArray(incomingData);

    Map<String,String> map=new HashMap<String,String>();

    for(int i=0;i<jsonArray.length();i++){
         JSONObject j = jsonArray.getJSONObject(i);
         Iterator<?> it = j.keys();
         while (it.hasNext()) {
              String n =  it.next().toString();
              map.put(n, j.getString(n));
           }
    }

但是当我执行此代码时,它会抛出异常。

org.json.JSONException: JSONObject["low_stock_date"] not a string.

使用JsonArray

[
  {
    "item_id": "1",
    "product_id": "1",
    "stock_id": "1",
    "qty": "99.0000",
    "low_stock_date": null
  },
  {
    "item_id": "2",
    "product_id": "2",
    "stock_id": "1",
    "qty": "100.0000",
    "low_stock_date": null
  }
]

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:0)

low_stock_date的值为null。这就是为什么它会抛出这个错误。

在将null添加到地图之前,只需添加一个支票。

if(!j.isNull(n)){
        map.put(n, j.getString(n));
}
else{
        map.put(n, null);
}

答案 1 :(得分:0)

for(int i=0;i<jsonArray.length();i++){
     JSONObject j = jsonArray.getJSONObject(i);
     Iterator<?> it = j.keys();
     while (it.hasNext()) {
          String n =  it.next().toString();
          map.put(n, j.getString(n));
       }
}

你正在做上面的内部,循环和放大在Map中存储键/值对。 由于每个JSONObject都有相同的键,因此只有最后一个jsonobject中的值才会出现在Map键中。 作为替代方案,您可以创建ArrayList来存储这些地图,您可以在将每个JSONObject转换为Map

时获取这些地图

您可以在这里做的另一件事是使用像Jackson Parser

这样的解析器

HashMap<String,String> result = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class); (其中JSON_SOURCE是文件,输入流,阅读器或json内容字符串)。

那会很快&amp;做你想做的更好的方式。

答案 2 :(得分:0)

这实际上是该方法的实现方式:

/**
 * Get the string associated with a key.
 *
 * @param key
 *            A key string.
 * @return A string which is the value.
 * @throws JSONException
 *             if there is no string value for the key.
 */
public String getString(String key) throws JSONException {
    Object object = this.get(key);
    if (object instanceof String) {
        return (String) object;
    }
    throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}

您可以检查要加载的对象的类型以查看它是否为空:

j.isNull(n);

然后采取相应行动:

if (j.isNull(n)) {
    // do something
} else {
    // do something else
}