Wednesday, October 2, 2013

JSON String to Object transformer



Consider you have a Simple Json with two values ( lable and value )  to read and these have to map to the POJO Class - ContentType .

 JSON Data


[

    {
        "label": "Movies",
        "value": "movie"
    },
    {
        "label": "TV Shows",
        "value": "tvshow"
    }

]


POJO

public class ContentType {
 
 
 private String label;
 private String value;

 public String getLabel() {
  return label;
 }
 public void setLabel(String label) {
  this.label = label;
 }
 public String getValue() {
  return value;
 }
 public void setValue(String value) {
  this.value = value;
 }

}

Jackson ObjectMapper for Reading

It can be reaad by using the Jackson mapper , as shown below . reply - has the POJO string shown above

ObjectMapper mapper = new ObjectMapper();   
List<contenttype> ctl = mapper.readValue(reply, List.class);

Package : org.codehaus.jackson.map

Library can be included in the project by using the following in the pom.xml or just get the latest from http://jackson.codehaus.org/

 pom.xml

 
    <dependency>
      <groupid>org.codehaus.jackson</groupid>
      <artifactid>jackson-mapper-asl</artifactid>
      <version>1.9.13</version>
    </dependency>
    
    <dependency>
      <groupid>org.codehaus.jackson</groupid>
      <artifactid>jackson-core-asl</artifactid>
      <version>1.9.13</version>
    </dependency> 
Using Generics you can have a utility to parse data in JSON and get String data from POJO
 
package util;

import java.util.ArrayList;
import java.util.HashMap;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.map.DeserializationConfig;

public class JsonStringConverter {

public static final <E> String getAsJSON(E inClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(inClass) ;
}

public static final <E> E parseAsInputClassForArrayList(String json,Class outClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
TypeFactory t = TypeFactory.defaultInstance();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return (E) mapper.readValue(json,t.constructCollectionType(ArrayList.class,outClass));
}

public static final <E> E parseAsInputClassForSimpleClass(String json,Class outClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return (E) mapper.readValue(json,outClass);
}

public static final <E> E parseAsInputClassForHashMap(String json,Class key,Class outClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
TypeFactory t = TypeFactory.defaultInstance();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return (E) mapper.readValue(json,t.constructMapType(HashMap.class,key,outClass));
}

}

No comments: