我构建了一个 json 对象,该对象由 Hashmap 中定义的 nameValue 对组成
我遇到的问题是当我调用时:
jsonObject.put(hashmap);
它像这样添加 nameValue 对:
name=value
代替name:value
有什么想法吗?
谢谢
使用 JSONObject 构造函数。不要创建自己的,因为您可能会错过某些情况,例如值是数组时。
JSONObject jsonObject = new JSONObject(hashMap);
这实际上是一个完整的解决方案,因为它涵盖了极端情况,例如值是数组的情况。因此,它将为您将其设为 JSONArray。
遍历 HashMap 并放入 jsonObject:
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
jsonObject.put(pairs.getKey(), pairs.getValue() );
}