-1

I have a json string

{

  {

     key1:[values1]
  },

  {

     key2:[values2]
  }

}

I want to convert it into HashMap(String,Object) in java.

I have been using normal json parsing, where I create a jsonObject from the json string and extract jsonArrays from the jsonObject. Is there any direct API to convert it?

Liju Thomas
  • 968
  • 5
  • 16
  • 24
ranjith Gampa
  • 105
  • 2
  • 12

1 Answers1

4

Always use jackson for JSON manipulation.

Check this out for other useful examples: https://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/

Regarding your question:

public class JsonMapExample {

public static void main(String[] args) {

    try {

        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"name\":\"mkyong\", \"age\":29}";

        Map<String, Object> map = new HashMap<String, Object>();

        // convert JSON string to Map
        map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});

        System.out.println(map);

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        }
    }

}
tmpg
  • 83
  • 6
  • Thank you, one of my friend was telling about jackson api, but I was not able to find relevant examples. This one is close to my json format – ranjith Gampa Aug 02 '16 at 05:43
  • Np. Examples are the best way to learn! – tmpg Aug 02 '16 at 05:56
  • `Map map = new ObjectMapper().readValue(json, Map.class)` works for me. With TypeReference, I have to override the getTypeName() method – Sourabh Apr 07 '21 at 10:46