简体   繁体   中英

How to convert Object type to HashMap

I'm trying to parse JSON my own way and I'm stuck on converting List to Map:

   public static void main ( final String[] args ) throws Exception
   {
      {
         String test = new String("[{\"label\": 1, \"value\": 12345}, {\"label\": 2, \"value\": 12}]");
         final StringReader stringReader = new StringReader(test);
         final Object obj = new JSONReader( stringReader ).parseData();
         List list = (List)obj;  // [{label=1, value=12345}, {label=2, value=12}] looks good
         System.out.println(list);
         for (Object o : list) {
             System.out.println(o);  // {label=1, value=12345} {label=2, value=12} also looks ok
                     if (!(o instanceof Map)) {
            throw new IllegalArgumentException("Root object must be a JSON object.");
        }
         }
      }

The following code doesn't throw exception thus the o is instance of Map. However I can't use the o.get("label") to retrieve the label value. How can I get every value from label and value field?

Actually it works with objectMapper

@Test
void t2() throws IOException {
    String test = new String("[{\"label\": 1, \"value\": 12345}, {\"label\": 2, \"value\": 12}]");
    final StringReader stringReader = new StringReader(test);
    final Object obj = new ObjectMapper().readValue(stringReader, Object.class);
    List list = (List)obj;  // [{label=1, value=12345}, {label=2, value=12}] looks good
    System.out.println(list);
    for (Object o : list) {
        System.out.println(o);  // {label=1, value=12345} {label=2, value=12} also looks ok
        if (!(o instanceof Map)) {
            throw new IllegalArgumentException("Root object must be a JSON object.");
        }
        System.out.println(((Map)o).get("label"));
    }
}

The output is;

[{label=1, value=12345}, {label=2, value=12}]
{label=1, value=12345}
1
{label=2, value=12}
2

This may be due to the JsonReader that you are using. I cannot figure out the parser with parseData method...

You should try to remove the keyword Object . That way you are not sure what you are parsing and it can happen that the element that you get is not a list .

I would go with the JSON Java Library . And then parse the value this way:

String test = "[{\"label\": 1, \"value\": 12345}, {\"label\": 2, \"value\": 12}]";
JSONArray jsonArray = new JSONArray(test);

for (Object o : jsonArray)
{
    JSONObject jsonObject = (JSONObject) o;
    System.out.println(jsonObject);
}

As you can see JSONArray and JSONObject can be used for the parsing. And they provide several functions that help on working with them.

My method proposition uses simple org.json library (2009) and is quite different:

private Map<Integer, Integer> convertJsonToMap(String test) throws JSONException {
    Map<Integer, Integer> map = new HashMap<>();
    JSONArray jsonArray = new JSONArray(test);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        if (jsonObject.length() == 2) {
            map.put((Integer) jsonObject.get(jsonObject.names().getString(0)),
                    (Integer) jsonObject.get(jsonObject.names().getString(1)));
        }
    }
    return map;
} 

Returns only Integers and could throw ClassCastException if any "label" or "value" is String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM