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)?

7
  • 2
    Have you looked at JSON libraries such as Jackson? Commented Nov 16, 2016 at 9:31
  • 1
    Well, a json object isn't a List<Map<String, String>>, it's more of a Map<String, Object>, where Object can be a List<Map<String, Object>> or a List<Object> (and those nested Objects 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) Commented Nov 16, 2016 at 9: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? Commented Nov 16, 2016 at 9:38
  • mkyong.com/java/how-to-convert-java-object-to-from-json-jackson check this Commented Nov 16, 2016 at 9:40
  • Serializing and de-serializing is fine if your json object doesn't vary. Am I correct? But in my case, it will vary. Commented Nov 16, 2016 at 9:45

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

See also link solution by peeskillet.
This is definitely what I was looking for. :)
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();
    }

}

}

4 Comments

Serializing and de-serializing is fine if your json object doesn't vary. Am I correct? But in my case, it will vary.
If your json structure variation is unpredictable then JSON tree is the only option IMHO.
I will check if this works for me. stackoverflow.com/questions/13916086/…
Thanks for apprising me :) I will check it to
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()

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.