2

I want to map below Json data to java object of List<Map<String, String>> type.

Sample Json:

{ 
  {
    a:b,
    c:d
  },
  {
    e:f,
    g:h,
    i:j
  },
  { 
   h:k
  }
}

Here a:b represents key-value pair. So a:b and c:d will be mapped to first map of the list and so on. one way to do this is by building JSON tree and access each node and store the pair into the map.

Is there a better way to do this (cleaner approach)?

VedantK
  • 9,728
  • 7
  • 66
  • 71
Yogesh
  • 255
  • 5
  • 16
  • 2
    Have you looked at JSON libraries such as Jackson? – Gelunox Nov 16 '16 at 09:31
  • 1
    Well, a json object isn't a `List>`, it's more of a `Map`, where `Object` can be a `List>` or a `List` (and those nested `Object`s can be the same two things as well). As for parsing it, I would personally use a json library but it's basically down to a state machine at that point (on the input symbols) – Rogue Nov 16 '16 at 09:32
  • Try using a real data sample instead.. Using gson you can easily create a data-class that matches the JSON-object and (de)serialize it with minimal effort. Is the structure of the JSON-object going to vary wildly? – Emil Kantis Nov 16 '16 at 09:38
  • https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ check this – VedantK Nov 16 '16 at 09:40
  • Serializing and de-serializing is fine if your json object doesn't vary. Am I correct? But in my case, it will vary. – Yogesh Nov 16 '16 at 09:45
  • Using Jackson, http://javabycode.com/java-core/json-tutorial/convert-java-object-tofrom-json-using-jackson-api.html check this. – David Pham Nov 16 '16 at 09:47
  • Or Using Gson, http://javabycode.com/java-core/json-tutorial/convert-collections-into-json-and-json-to-collections.html check this – David Pham Nov 16 '16 at 09:48

4 Answers4

1

Here is the code to read a List<Map<String, String>> using the Jackson library, with your example data as input:

public class JsonTest {
public static void main(String[] args) throws Exception {
    final String json
        = "[\n"
        + "    {\n"
        + "        \"a\":\"b\",\n"
        + "        \"c\":\"d\"\n"
        + "    },\n"
        + "    {\n"
        + "        \"e\":\"f\",\n"
        + "        \"g\":\"h\",\n"
        + "        \"i\":\"j\"\n"
        + "    },\n"
        + "    {\n"
        + "        \"h\":\"k\"\n"
        + "    }\n"
        + "]"; // [{a:b,c:d},{e:f,g:h,i:j},{h:k}]   
    ObjectMapper mapper = new ObjectMapper();
    TypeFactory factory = TypeFactory.defaultInstance();
    List<Map<String, String>> list = mapper.readValue(json,factory
        .constructCollectionType(List.class, factory
                .constructMapType(Map.class, String.class, String.class)));
    System.out.println(list.toString());
}
}

Note: I had to fix your outermost braces from {} to [], which is the correct JSON list syntax.

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
0

You can use Jackson to achieve this task through below example code

public class JacksonExample {
public static void main(String[] args) {

    ObjectMapper mapper = new ObjectMapper();

    try {

        // Convert JSON string from file to Object
        User user = mapper.readValue(new File("C:\\user.json"), User.class);
        System.out.println(user);

        // Convert JSON string to Object
        String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"xyz\"}";
        User user1 = mapper.readValue(jsonInString, User.class);
        System.out.println(user1);

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

}

}

0

Just use gson library to Json to object and object to Json

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

Object to Json

Gson gson = new Gson();
Student obj=new Student();
String jsonInString = gson.toJson(obj);

Json To Object

Student obj = gson.fromJson(jsonInString, Student.class);
Mark Storer
  • 15,672
  • 3
  • 42
  • 80
Er Kapil Mehta
  • 79
  • 2
  • 11
0

First I made few changes to your json to make it valid

{
"key": 
    [{
        "a": "b",
        "c": "d"
    },
    {
        "e": "f",
        "g": "h",
        "i": "j"
    }, 
    {
        "h": "k"
    }]

}

Please find the below code that I have tried out :

ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode1 = mapper.createObjectNode();
Map<String, Object> i = mapper.readValue(new File("J:/temp/sample.json"), Map.class);
System.out.println(i.get("key"));
System.out.println(i.values());

Output :

//For System.out.println(i.get("key"));

[{a=b, c=d}, {e=f, g=h, i=j}, {h=k}]

//For System.out.println(i.values());

[[{a=b, c=d}, {e=f, g=h, i=j}, {h=k}]]

If the above approach helps you, Make a right decision based on your needs either i.get("key") or i.values()

Mouli
  • 299
  • 3
  • 12