Parsing JSON string in android

后端 未结 2 634
迷失自我
迷失自我 2020-12-07 02:19

Parsing JSON seems like it is a pretty common topic of discussion on here. I have looked around and still have not found what I am looking for. Here is my code for my HttpC

相关标签:
2条回答
  • 2020-12-07 02:26

    In this case you can use the keys method of the JSONObject class. It will basically returns an Iterator of the keys, that you can then iterate to get and put the values in a map:

    try {
        JSONObject jsonObject = new JSONObject(theJsonString);
        Iterator keys = jsonObject.keys();
        Map<String, String> map = new HashMap<String, String>();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, jsonObject.getString(key));
        }
        System.out.println(map);// this map will contain your json stuff
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-12-07 02:41

    Note that Jackson can deserialize either of the two JSON examples very simply.

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> values = mapper.readValue(theJsonString, Map.class);
    

    Gson can do it similarly simply if you're satisfied with a Map<String, String>, instead of a Map<String, Object>. Currently, Gson would need custom deserialization for a Map<String, Object>.

    0 讨论(0)
提交回复
热议问题