How to Convert JSON string to Map.

How to Convert JSON string to Map.

This articles focus on how to convert JSON string to/from a Map, before moving to the java code to convert JSON to/from map, likely ask questions are

1. What do I need JSON for ?

2. What is the benfit of JSON …?

In the ‘old’ days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight.

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

In summary – JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized.

Now let’s start

1. JSON string to Map

MyJsonMap.java

package com.examp.myjson;
      import java.io.IOException;
      import java.util.HashMap;
      import java.util.Map;
      import com.fasterxml.jackson.core.JsonGenerationException;
      import com.fasterxml.jackson.core.type.TypeReference;
      import com.fasterxml.jackson.databind.JsonMappingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
public class MyJsonMap {
   public static void main(String[] args) {
      try {
         ObjectMapper mapper = new ObjectMapper();
         String json = "{\"name\":\"Amuda-Adeolu-Badmus\", \"age\":24}";
         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();
      }
   }
}

Output
      {name=Amuda-Adeolu-Badmus, age=24}

2. Map to JSON string
convert Map to JSON string
MyMapJson.java

package com.examp.myjson;
      import java.io.IOException;
      import java.util.HashMap;
      import java.util.Map;
      import com.fasterxml.jackson.core.JsonGenerationException;
      import com.fasterxml.jackson.databind.JsonMappingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
public class MyMapJson{
   public static void main(String[] args) {
      try {
         ObjectMapper mapper = new ObjectMapper();
         String json = "";
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("name", "Amuda-Adeolu-Badmus");
         map.put("age", 24);
// convert map to JSON string
         json = mapper.writeValueAsString(map);
         System.out.println(json);
         json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
// pretty print
         System.out.println(json);
      } catch (JsonGenerationException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}


Output

      {"name":"Amuda-Adeolu-Badmus","age":24}
      {
      "name" : "Amuda-Adeolu-Badmus",
      "age" : 24
      }

3. Map to JSON File

JsonMapFile.java

      package com.examp.myjson;
      import java.io.*;
      import java.util.*;

      import com.fasterxml.jackson.core.JsonGenerationException;
      import com.fasterxml.jackson.databind.JsonMappingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonMapFile {
   public static void main(String[] args) {
      try {
         ObjectMapper mapper = new ObjectMapper();
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("name", "Amuda-Adeolu-Badmus");
         map.put("age", 24);
         List list = new ArrayList<>();
         list.add("msg 1");
         list.add("msg 2");
         list.add("msg 3");
         map.put("messages", list);
// write JSON to a file
         mapper.writeValue(new File("c:\\user.json"), map);
      } catch (JsonGenerationException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}


c:\\user.json
      {"name":"Amuda-Adeolu-Badmus","messages":["msg 1","msg 2","msg 3"],"age":24}

4. JSON file to Map
JsonFileMapII.java
package com.example.myjson;
      import java.io.*;
      import java.util.*;
      import java.util.Map;
      import com.fasterxml.jackson.core.JsonGenerationException;
      import com.fasterxml.jackson.core.type.TypeReference;
      import com.fasterxml.jackson.databind.JsonMappingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonFileMapII {
   public static void main(String[] args) {
      try {
         ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
         Map<String, Object> map = mapper.readValue(
               new File("c:\\user.json"),
               new TypeReference<Map<String, Object>>() {
               });
         System.out.println(map.get("name"));
         System.out.println(map.get("age"));
         @SuppressWarnings("unchecked")
         ArrayList list = (ArrayList) map.get("messages");
         for (String msg : list) {
            System.out.println(msg);
         }
      } catch (JsonGenerationException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}


Output
      Amuda-Adeolu-Badmus
      24
      msg 1
      msg 2
      msg 3
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: