Friday 15 September 2017

Convert json string to map

Below program converts json string to a map. This program runs only for primitive types. If json string has complex types like array, nested json objects, it will not work.

Test.java
import java.util.LinkedHashMap;
import java.util.Map;

public class Test {

 public static Map<String, String> getMapFromString(String s) {
  if (s == null || s.isEmpty()) {
   return new LinkedHashMap<>();
  }

  Map<String, String> map = new LinkedHashMap<>();

  String[] tokens = s.split(",");

  for (int i = 0; i < tokens.length; i++) {
   tokens[i] = tokens[i].replace("\"", "");
   tokens[i] = tokens[i].replace("{", "");
   tokens[i] = tokens[i].replace("}", "");
   String[] subparts = tokens[i].split(":");

   if (subparts.length == 2) {
    map.put(subparts[0], subparts[1]);
   } else {
    map.put(subparts[0], "");

   }

  }

  return map;
 }

 public static void main(String args[]) {

  String json = "{\"id\":\"123456\",\"changeToken\":\"token-1234\",\"headerText\":\"\"}";

  Map<String, String> map = getMapFromString(json);

  for (String key : map.keySet()) {
   System.out.println(key + " : " + map.get(key));
  }
 }
}

Output
id : 123456
changeToken : token-1234
headerText :

If you would like to convert complex json string to map, I would suggest you to use libraries like gson, Jackson, genson etc.,



You may like




No comments:

Post a Comment