I want to use Jackson to serialize an object include a generic collection type.
This is the interface:
public interface PagingAdapter <Id extends Serializable, T extends Entity<Id>> extends Serializable {
public List<T> getItem();
public void setItem(List<T> items);
public Boolean hasNextPage();
public Integer getTotalPage();
public Integer getPageSize();
public void setPageSize(int pageSize);
public Long getTotalItem();
public void setTotalItem(Long totalItem);
public void setCurrentPage(Integer currentPage);
public Integer getCurrentPage();
public Class<T> getEntityType();
public void setEntityType(Class<T> entityType);
}
and this is the implementation:
public class PagingAdapterImpl<Id extends Serializable, T extends Entity<Id>> implements
PagingAdapter<Id,T> {
private static Integer DEFAULT_PAGE_SIZE = 20;
private Class<T> entityType;
private List<T> items = null;
private Integer pageSize = DEFAULT_PAGE_SIZE;
private Integer currentPage = 0;
private Long totalItem;
public PagingAdapterImpl(List<T> items, int currentPage, int pageSize, long totalItem) {
super();
this.items = items;
this.pageSize = pageSize;
this.currentPage = currentPage;
this.totalItem = totalItem;
}
public PagingAdapterImpl(){
}
#Override
public Class<T> getEntityType() {
return entityType;
}
#Override
public void setEntityType(Class<T> entityType) {
this.entityType = entityType;
}
#Override
public List<T> getItem() {
return items;
}
#Override
public void setItem(List<T> items) {
this.items = items;
}
#Override
public Boolean hasNextPage() {
return false;
}
#Override
public Integer getTotalPage() {
int rs = (int) (getTotalItem() % getPageSize() == 0 ? getTotalItem()
/ getPageSize() : getTotalItem() / getPageSize() + 1);
return 0;
}
#Override
public Integer getPageSize() {
return this.pageSize;
}
#Override
public Long getTotalItem() {
return this.totalItem;
}
#Override
public void setTotalItem(Long totalItem) {
this.totalItem = totalItem;
}
#Override
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
#Override
public Integer getCurrentPage() {
return currentPage;
}
#Override
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
I'm using RestEasy with Jackson 1.9. Output of a rest method return instance of this object now like this:
{
"status": 0,
"data": {
"entityType": null,
"pageSize": 1,
"currentPage": 1,
"totalItem": 1,
"item": [],
"totalPage": 0
}
}
The "item" property cannot be serialized to a JSON array. How can I fix this problem?
public class PagingAdapterSerializer extends JsonSerializer<PagingAdapter<Long, Entity<Long>>> {
#Override
public void serialize(PagingAdapter<Long, Entity<Long>> value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField("item",value.getItem());
jgen.writeObjectField("totalItem",value.getTotalPage());
jgen.writeObjectField("pageSize",value.getPageSize());
jgen.writeObjectField("totalItem",value.getTotalItem());
jgen.writeObjectField("currentPage",value.getCurrentPage());
jgen.writeEndObject();
}
This is my custom serializer. But it doesn't works
Instead of writing each object to JsonGenerator, you can below code to serialize it for a defined object.
String toJson(Object object){
JSONSerializer ser = new JSONSerializer().transform(new ExcludeNullTransformer(), void.class);
ser.exclude("*.class");
return ser.serialize(object);
}
Include dependency for latest jackson in your code.
Related
I am trying to trim the JSON key in order to avoid spaces in the JSON requests.
JSON Object would look like with white space, (check for "eq")
{
"page": 0,
"size": 25,
"and":{
"eq ": [
{
"field":"id",
"value": "60536"
}
]
}
}
I find lot of solution ranging from SimpleModule to JsonDeserializer but all generally work on the value part. How can I trim the key itself which then correctly converts into my Java POJO?
public class SearchInDTO implements InDTO {
private Integer pageNo;
private Integer pageSize;
private ANDFilter andFilter;
#JsonProperty("page")
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
#JsonProperty("size")
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
#JsonProperty("and")
public ANDFilter getAndFilter() {
return andFilter;
}
public void setAndFilter(ANDFilter andFilter) {
this.andFilter = andFilter;
}
public static class EQFilter extends FieldValue
{
#JsonProperty("field")
public String getFieldName() {
return super.getFieldName();
}
#JsonProperty("value")
public String getValue() {
return super.getValue();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("EQFilter{");
sb.append(super.toString());
sb.append('}');
return sb.toString();
}
}
public static class FieldValue
{
private String fieldName;
private String value;
#JsonProperty("field")
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("value")
public String getValue() {
if(value == null) return value;
return value.toLowerCase();
}
public void setValue(String value) {
this.value = value;
}
}
public static class ANDFilter {
private List<EQFilter> eqFilters = new ArrayList<>();
#JsonProperty("eq")
public List<EQFilter> getEqFilters() {
return eqFilters;
}
public void setEqFilters(List<EQFilter> eqFilters) {
this.eqFilters = eqFilters;
}
}
}
Solution with custom JsonParser implementation:
public class MyJsonParser extends JsonParserDelegate {
public MyJsonParser(JsonParser parser) {
super(parser);
}
#Override
public String getCurrentName() throws IOException {
return super.getCurrentName().trim();
}
}
public class MyJsonParserFactory extends MappingJsonFactory {
#Override
protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(in, ctxt));
}
#Override
protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(r, ctxt));
}
#Override
protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable) throws IOException {
return new MyJsonParser(super._createParser(data, offset, len, ctxt, recyclable));
}
#Override
protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(data, offset, len, ctxt));
}
#Override
protected JsonParser _createParser(DataInput input, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(input, ctxt));
}
}
#Component
public class MyJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
#Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.factory(new MyJsonParserFactory());
}
}
I want to extract "msg" value from below json using fasterxml.jackson - Can anyone suggest me how my model class should look like?
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Bad data received",
"err_data": {
"payment_details.type": {
"location": "body",
"param": "payment_details.type",
"msg": "Must be either etransfer or cheque"
}
}
}
This is what I have done, but it is always returning "null" !
#JsonInclude(JsonInclude.Include.ALWAYS)
public class MyApiResponse extends ParentResponse implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("payment_details")
private PaymentDetails payment_details;
#JsonProperty("payment_details")
public PaymentDetails getPayment_details() {
return payment_details;
}
#JsonProperty("payment_details")
public void setPayment_details(PaymentDetails payment_details) {
this.payment_details = payment_details;
}
}
ParentResponse model class extends ErrorResponse model class and this is how it looks like..
This ErrorResponse model represents above mentioned JSON.
#JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResponse implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("statusCode")
private int statusCode;
#JsonProperty("error")
private String error;
#JsonProperty("message")
private String message;
#JsonProperty("err_data")
private ErrData err_data;
#JsonProperty("statusCode")
public int getStatusCode() {
return statusCode;
}
#JsonProperty("statusCode")
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
#JsonProperty("message")
public String getMessage() {
return message;
}
#JsonProperty("message")
public void setMessage(String message) {
this.message = message;
}
#JsonProperty("error")
public String getError() {
return error;
}
#JsonProperty("error")
public void setError(String error) {
this.error = error;
}
#JsonProperty("err_data")
public ErrData getErr_data() {
return err_data;
}
#JsonProperty("err_data")
public void setErr_data(ErrData err_data) {
this.err_data = err_data;
}
}
err_data object is represented by below model class.
#JsonInclude(JsonInclude.Include.ALWAYS)
public class ErrData implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("email")
private Email email;
#JsonProperty("payment_details.type")
private PaymentDetailsType payment_details_type;
#JsonProperty("email")
public Email getEmail() {
return email;
}
#JsonProperty("email")
public void setEmail(Email email) {
this.email = email;
}
#JsonProperty("payment_details.type")
public PaymentDetailsType getPayment_details_type() {
return payment_details_type;
}
#JsonProperty("payment_details.type")
public void setPayment_details_type(PaymentDetailsType payment_details_type) {
this.payment_details_type = payment_details_type;
}
}
payment_details.type object represented by below class.
#JsonInclude(JsonInclude.Include.ALWAYS)
public class PaymentDetailsType extends ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
}
#JsonInclude(JsonInclude.Include.ALWAYS)
public class Email extends ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
}
And finally ErrorMessage which is extended by PaymentDetailsType as below.
#JsonPropertyOrder({"location", "param", "value", "msg"})
public class ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("location")
private String location;
#JsonProperty("param")
private String param;
#JsonProperty("value")
private String value;
#JsonProperty("msg")
private String msg;
#JsonProperty("location")
public String getLocation() {
return location;
}
#JsonProperty("location")
public void setLocation(String location) {
this.location = location;
}
#JsonProperty("param")
public String getParam() {
return param;
}
#JsonProperty("param")
public void setParam(String param) {
this.param = param;
}
#JsonProperty("value")
public String getValue() {
return value;
}
#JsonProperty("value")
public void setValue(String value) {
this.value = value;
}
#JsonProperty("msg")
public String getMsg() {
return msg;
}
#JsonProperty("msg")
public void setMsg(String msg) {
this.msg = msg;
}
}
And finally I am trying to get "msg" field value as below -
new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getPayment_details_type().getMsg();
I think there is something wrong with this one - Not sure how to define getter method if field name in json as . (dot).
#JsonProperty("payment_details.type")
public PaymentDetailsType getPayment_details_type() {
return payment_details_type;
}
Similar to above, I am doing it for below json to retrieve "msg" value and it is working fine.
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Bad data received",
"err_data": {
"email": {
"location": "body",
"param": "email",
"value": "test # com",
"msg": "Must be a valid email"
}
}
}
This is returning correct "msg" value.
new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getEmail().getMsg();
Please suggest!
Thank you.
Here is a minimal example showing how to parse a JSON with Jackson, where the property names may contain dots:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
class Main {
public static void main(String[] args) throws IOException {
String json = "{" +
" \"payment_details.type\": {" +
" \"location\": \"body\"" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(json, Response.class);
System.out.println(response.getPaymentDetailsType().getLocation());
}
}
class Response {
#JsonProperty("payment_details.type")
private PaymentDetailsType paymentDetailsType;
public PaymentDetailsType getPaymentDetailsType() { return paymentDetailsType; }
}
class PaymentDetailsType {
private String location;
public String getLocation() { return location; }
}
Note that you only need #JsonProperty when the expected property name in JSON cannot be deduced from a setter or variable name
Its also working with #JsonProperty.
You just have to escape the dot:
#JsonProperty("payment_details\\.type")
I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}
I need to store an object using Hibernate, but this object use an enum. I can store, but when I tried to retrieve it again, this fails with this error: "Studies is not mapped [FROM Studies]".
I tried with a lot of solutions in internet but nothing works. I use MySQL database
This is the enum:
public enum StudyStatus {
Created("Created"), Started("Started"), Closed("Closed");
private final String value;
StudyStatus(String value){
this.value = value;
}
public static StudyStatus fromValue(int value){
for (StudyStatus status : values()) {
if (status.value.equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Invalid status: " + value);
}
public String toValue(){
return value;
}
}
This is the EnumUserType class
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.AbstractStandardBasicType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.usertype.EnhancedUserType;
import org.hibernate.usertype.ParameterizedType;
public abstract class AbstractEnumUserType<E extends Enum<E>, V> implements
EnhancedUserType, ParameterizedType {
public static int DEAFAULT_SQL_TYPE = Types.INTEGER;
private PreparedStatementSetter psSetter;
private AbstractStandardBasicType<?> basicType;
protected abstract Class<E> getEnumClass();
protected abstract Class<V> getValueClass();
protected abstract E convertEnum(V rawValue);
protected abstract V convertSqlValue(E enumValue);
protected int getSqlType() {
int sqlType = Types.OTHER;
switch (getValueClass().getName()) {
case "java.lang.String":
sqlType = Types.VARCHAR;
break;
case "java.lang.Integer":
sqlType = Types.INTEGER;
break;
default:
break;
}
return sqlType;
}
// ////////////////////////////
#Override
public int[] sqlTypes() {
return new int[] { getSqlType() };
}
#Override
public Class<?> returnedClass() {
return getEnumClass();
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
return (x == y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return (x == null) ? 0 : x.hashCode();
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Object rawValue = basicType.nullSafeGet(rs, names[0], session, owner);
Object enumValue = (rawValue == null) ? null
: convertEnum((V) rawValue);
return enumValue;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
psSetter.set(st, convertSqlValue((E) value), index);
}
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
#Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
#Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
#Override
public void setParameterValues(Properties parameters) {
// Initialize Method
initBasicType();
initPreparedStatementSetter();
}
#Override
public String objectToSQLString(Object value) {
return '\'' + ((Enum<?>) value).name() + '\'';
}
#Override
public String toXMLString(Object value) {
return ((Enum<?>) value).name();
}
#Override
public Object fromXMLString(String xmlValue) {
// TODO
throw new IllegalAccessError();
// return Enum.valueOf(, xmlValue);
}
protected void initBasicType() {
switch (getSqlType()) {
case Types.VARCHAR:
basicType = StringType.INSTANCE;
break;
case Types.INTEGER:
basicType = IntegerType.INSTANCE;
break;
default:
break;
}
}
protected void initPreparedStatementSetter() {
// TODO
switch (getSqlType()) {
case Types.VARCHAR:
psSetter = new StringPreparedStatementSetter();
break;
case Types.INTEGER:
psSetter = new IntPreparedStatementSetter();
default:
break;
}
}
private static interface PreparedStatementSetter {
void set(PreparedStatement st, Object value, int index)
throws SQLException;
}
private static class StringPreparedStatementSetter implements
PreparedStatementSetter {
#Override
public void set(PreparedStatement st, Object value, int index) {
try {
st.setString(index, (String) value);
} catch (SQLException e) {
}
}
}
private static class IntPreparedStatementSetter implements
PreparedStatementSetter {
#Override
public void set(PreparedStatement st, Object value, int index) {
try {
st.setInt(index, (Integer) value);
} catch (SQLException e) {
}
}
}
}
The class with the enum
import java.util.ArrayList;
import ateam.capi.common.enums.StudyStatus;
public class Study {
private String id;
private String name;
private StudyStatus status;
private ArrayList<User> pollsters;
private Questionnaire actualQuestionnaire;
public Questionnaire getActualQuestionnaire() {
return actualQuestionnaire;
}
public void setActualQuestionnaire(Questionnaire actualQuestionnaire) {
this.actualQuestionnaire = actualQuestionnaire;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StudyStatus getStatus() {
return status;
}
public void setStatus(StudyStatus status) {
this.status = status;
}
public ArrayList<User> getPollsters() {
return pollsters;
}
public void setPollsters(ArrayList<User> pollsters) {
this.pollsters = pollsters;
}
}
This is the XML to map the Study class
<hibernate-mapping package="ateam.capi.common.beans">
<class name="Study" table="Studies">
<id name="id" column="id"></id>
<property name="name"/>
<property name="status">
<type name="ateam.capi.capipersistence.utils.EnumUserType">
<param name="enumClassName">
ateam.capi.common.enums.StudyStatus
</param>
</type>
</property>
</class>
</hibernate-mapping>
Study DAO class
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ateam.capi.capipersistence.utils.HibernateUtil;
import ateam.capi.common.beans.Questionnaire;
import ateam.capi.common.beans.Study;
public class DAO_Study {
private Session session;
private Transaction tx;
public void saveStudy(Study study) throws HibernateException{
try{
initOperations();
session.save(study);
tx.commit();
} catch (HibernateException ex){
handleException(ex);
throw ex;
} finally{
if (session!=null){
session.close();
}
}
}
public void deleteStudy(Study study) throws HibernateException{
try{
initOperations();
this.session.delete(study);
this.tx.commit();
} catch (HibernateException ex){
handleException(ex);
throw ex;
} finally{
if (session!=null){
session.close();
}
}
}
public List<Study> getStudiesList() throws HibernateException{
List<Study> studiesList = null;
try{
initOperations();
String hql = "FROM Studies";
Query query = session.createQuery(hql);
studiesList = query.list();
} catch (HibernateException ex){
handleException(ex);
throw ex;
} finally{
if (session!=null){
session.close();
}
}
return studiesList;
}
private void initOperations() throws HibernateException{
HibernateUtil.createSession();
this.session = HibernateUtil.getSessionFactory().openSession();
this.tx = this.session.beginTransaction();
}
private void handleException(HibernateException ex) throws HibernateException{
this.tx.rollback();
System.out.println(ex.getStackTrace());
throw ex;
}
}
I use Java7 with hibernate 4.1.8, I found other solutions but dont work in java7
Any Idea?
Thanks!
Shouldn't your query look like from study instead of from studies? Studies is the table not the defined entity.
I have a simple JSON statement which type is very per need. like this
{
actor:{name:"kumar",mbox:"kumar#gmail.com"}
verb :"completed"
}
or
{
actor:{name:["kumar","manish"],mbox:["kumar#gmail.com","manish#gmail.com"]}
verb :{
"id" : "http://adlnet.gov/expapi/verbs/completed",
"display" : {
"en-US" : "completed"
}
}
I am using using POJO class to map this json string and pojo class code is given bleow
#JsonProperty("actor")
Actor actor;
#JsonProperty("verb")
Verb objVerb;
#JsonProperty("verb")
String verb;
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
public Verb getObjVerb() {
return objVerb;
}
public void setObjVerb(Verb objVerb) {
this.objVerb = objVerb;
}
#JsonIgnore
public String getVerb() {
return verb;
}
#JsonIgnore
public void setVerb(String verb) {
this.verb = verb;
}
public static class Actor {
String objectType;
#JsonProperty("name")
ArrayList<String> listName;
#JsonProperty("name")
String name;
#JsonProperty("mbox")
ArrayList<String> listMbox;
#JsonProperty("mbox")
String mbox;
#JsonProperty("mbox_sha1sum")
ArrayList<String> Listmbox_sha1sum;
#JsonProperty("mbox_sha1sum")
String mbox_sha1sum;
#JsonProperty("openid")
String openid;
#JsonProperty("account")
Account account;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
#JsonIgnore
public String getName() {
return name;
}
#JsonIgnore
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getListMbox() {
return listMbox;
}
public void setListMbox(ArrayList<String> listMbox) {
this.listMbox = listMbox;
}
#JsonIgnore
public String getMbox() {
return mbox;
}
#JsonIgnore
public void setMbox(String mbox) {
this.mbox = mbox;
}
public ArrayList<String> getListmbox_sha1sum() {
return Listmbox_sha1sum;
}
public void setListmbox_sha1sum(ArrayList<String> listmbox_sha1sum) {
Listmbox_sha1sum = listmbox_sha1sum;
}
#JsonIgnore
public String getMbox_sha1sum() {
return mbox_sha1sum;
}
#JsonIgnore
public void setMbox_sha1sum(String mbox_sha1sum) {
this.mbox_sha1sum = mbox_sha1sum;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public static class Account {
#JsonProperty("homePage")
String homePage;
#JsonProperty("name")
String name;
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Verb {
String id;
Map<String,String> display;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getDisplay() {
return display;
}
public void setDisplay(Map<String, String> display) {
this.display = display;
}
}
I am using jaxb and jakson. I am implementing the webservice to handle the json statement
so I use the bean class to map with json. But when I use to map this json then it gives the following exceptions
org.codehaus.jackson.map.JsonMappingException : property with the name "mbox" have two entry.
Define a proper bean structure so it directly mapped to the beans class
Try to leave only #JsonProperty("mbox") ArrayList<String> listMbox; field (don't need #JsonProperty("mbox")
String mbox;)
and add Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY=true to Jackson object mapper config.
So in deserialization it will be able to get as both array and single element.
you can use gson.
class cls = gson.fromJson(jsonString, clazz);
here jsonString can be stringified java script object. gson.fromJson method can map your java script key to java property.