How to convert HashMap to json Array in android?

后端 未结 5 531
陌清茗
陌清茗 2020-12-03 03:20

I want to convert HashMap to json array my code is as follow:

Map map = new HashMap();

map.put(         


        
5条回答
  •  孤城傲影
    2020-12-03 04:01

    A map consists of key / value pairs, i.e. two objects for each entry, whereas a list only has a single object for each entry. What you can do is to extract all Map.Entry and then put them in the array:

    Set entries = map.entrySet();
    JSONArray mJSONArray = new JSONArray(entries);
    

    Alternatively, sometimes it is useful to extract the keys or the values to a collection:

    Set keys = map.keySet();
    JSONArray mJSONArray = new JSONArray(keys);
    

    or

    List values = map.values();
    JSONArray mJSONArray = new JSONArray(values);
    

    Note: If you choose to use the keys as entries, the order is not guaranteed (the keySet() method returns a Set). That is because the Map interface does not specify any order (unless the Map happens to be a SortedMap).

提交回复
热议问题