简体   繁体   中英

Convert json String containing array to Map in Java

I need to convert String to Map for the following json string in Java: Please note that this json string has array in it and that is where I am facing the issue:

{
   "type":"auth",
   "amount":"16846",
   "level3":{
      "amount":"0.00",
      "zip":"37209",
      "items":[
         {
            "description":"temp1",
            "commodity_code":"1",
            "product_code":"11"
         },
         {
            "description":"temp2",
            "commodity_code":"2",
            "product_code":"22"
         }
      ]
   }
}

I tried couple of ways as mentioned in below links:

Convert JSON string to Map – Jackson

Parse the JSONObject and create HashMap

Error I am getting:

JSON parser error: Can not deserialize instance of java.lang.String out of START_OBJECT token ... }; line: 3, column: 20] (through reference chain: java.util.LinkedHashMap["level3"])com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

So to give more details about what I am doing with the Map is, this map will be converted back to the json string using following method:

    public static String getJSON(Object map) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    OutputStream stream = new BufferedOutputStream(byteStream);
    JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(stream, JsonEncoding.UTF8);
    objectMapper.writeValue(jsonGenerator, map);
    stream.flush();
    jsonGenerator.close();
    return new String(byteStream.toByteArray());
}

You cannot parse your JSON content into a Map<String, String> (like it is done in the two links you posted). But you can parse it into a Map<String, Object> .

For example like this:

ObjectMapper mapper = new ObjectMapper();
File file = new File("example.json");
Map<String, Object> map;
map = mapper.readValue(file, new TypeReference<Map<String, Object>>(){});

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