Putting HashMap in jsonobject

后端 未结 3 894
礼貌的吻别
礼貌的吻别 2021-01-21 03:30

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);


        
相关标签:
3条回答
  • 2021-01-21 04:10

    Use JSON's putAll.

            Map<String, Object> myMap = new HashMap<String, Object>();
            JSONObject jsonObject = new JSONObject();
    
            jsonObject.putAll(myMap);
    
    0 讨论(0)
  • 2021-01-21 04:21

    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.

    0 讨论(0)
  • 2021-01-21 04:24

    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() );
    }
    
    0 讨论(0)
提交回复
热议问题