java 将 HashMap<String, object> 放入 jsonobject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17444396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Putting HashMap<String, object> in jsonobject
提问by Jonathan
i building a json object that consists of nameValue pairs defined in a Hashmap
我构建了一个由 Hashmap 中定义的 nameValue 对组成的 json 对象
the issue i am having is when i invoke:
我遇到的问题是当我调用:
jsonObject.put(hashmap);
It adds the nameValue pairs like this:
它添加了 nameValue 对,如下所示:
name=value
instead of name:value
name=value
代替 name:value
Any thoughts?
有什么想法吗?
Thanks
谢谢
回答by Multithreader
Use JSONObject constructor. DON"T CREATE YOUR OWN since you might miss some cases such when the value is an array.
使用 JSONObject 构造函数。不要创建您自己的,因为您可能会错过某些情况,例如当值是数组时。
JSONObject jsonObject = new JSONObject(hashMap);
This is actually a complete solution since it covers for corner cases such as where the value is an array. Thus, it will make it as JSONArray for you.
这实际上是一个完整的解决方案,因为它涵盖了极端情况,例如值是数组的情况。因此,它将为您制作 JSONArray。
回答by Jonathan Naguin
Iterate through the HashMap and put to the jsonObject:
遍历 HashMap 并放入 jsonObject:
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
jsonObject.put(pairs.getKey(), pairs.getValue() );
}
回答by Ghost Rider
Use JSON's putAll.
使用 JSON 的 putAll。
Map<String, Object> myMap = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject();
jsonObject.putAll(myMap);