Xdev Xdev - 17 days ago 5
Java Question

Json to Java Mapping

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

Answer

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.

Comments