Putting HashMap<String, object> in jsonobject

萝らか妹 提交于 2019-12-11 03:18:59

问题


i building a json object that consists of nameValue pairs defined in a Hashmap

the issue i am having is when i invoke:

jsonObject.put(hashmap);

It adds the nameValue pairs like this:

name=value instead of name:value

Any thoughts?

Thanks


回答1:


Iterate through the HashMap and put to the jsonObject:

Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    jsonObject.put(pairs.getKey(), pairs.getValue() );
}



回答2:


Use JSONObject constructor. DON"T CREATE YOUR OWN since you might miss some cases such when the value is an array.

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.




回答3:


Use JSON's putAll.

        Map<String, Object> myMap = new HashMap<String, Object>();
        JSONObject jsonObject = new JSONObject();

        jsonObject.putAll(myMap);


来源:https://stackoverflow.com/questions/17444396/putting-hashmapstring-object-in-jsonobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!