Create a pojo class of Json objects [using jackson]



//1. create a class to map the json data e.g
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;

import java.util.HashMap;
import java.util.Map;

/**
*
* @author Shishir Pokharel
*/
public class model {

// and then "other" stuff:
protected Map<String, Object> other = new HashMap<String, Object>();

// Two mandatory properties
protected final int id;
protected final String name;
protected final Long TimeStamp = System.currentTimeMillis();

// Could alternatively add setters, but since these are mandatory
@JsonCreator
public model(@JsonProperty("jsonid") int id, @JsonProperty("jsonname") String name) {
super();
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public Long getTimeStamp(){
return TimeStamp;
}
public Object get(String name) {
return other.get(name);
}

// "any getter" needed for serialization
@JsonAnyGetter
public Map<String, Object> getany() {
return other;
}

@JsonAnySetter
public void set(String name, Object value) {
other.put(name, value);
}
}

//2. Create second class to map the json objects to above pojo class

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

class mapperClass{

public mapperClass(){

}

public void createPojo(String MyJsonObject){

ObjectMapper mapper = new ObjectMapper();
if (mapper.readTree(txtMessage.getText()).isArray()) {
List<model> ArrayObjects = mapper.readValue(txtMessage.getText(), new TypeReference<List<model>>() {});
}else{
model SingleObject = mapper.readValue(txtMessage.getText(), new TypeReference<model>() {});
}

}

public static void main(String[] args){
mapperClass Mymapper = new mapperClass();
Mymapper.createPojo(json_objects);

}

}

Source file : http://jackson.codehaus.org/1.9.2/jackson-all-1.9.2.jar
Java Docs : http://jackson.codehaus.org/1.9.2/javadoc/index.html

, , , , ,

Comments are closed.