Can Jackson be configured to deserialize the JSON Key (Not value)? - json

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

Related

Jackson serialize generic collection

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.

415 error while trying to post json array to spring rest controller

My json request is as follows
{
"division":"XX",
"category":"XX",
"operation":"XXX",
"transactionId":"XX",
"trackNumber":"XXx",
"attentionReason":"",
"carNeedAttention":"",
"chargableDamage":"X",
"missingItems":"",
"offences":"N",
"outInAgentNumber":"XX",
"cList":{
{
"id":"230",
"elementCode":"XXX",
"value":"XXX",
"comment":"XX",
"label":"",
"uiComponent":"",
"featureType":""
}
},
"outInCprNumber":"XX",
"outInDate":"",
"outInDuration":"",
"outInFuel":"75",
"outInKm":"9999",
"outInRem1":"",
"outInRem2":"",
"outInRem3":"",
"userName":"XX",
"vehicleRetBy":""
}
I have a spring rest controller class
#Controller
#RequestMapping("/services")
public class CheckListController {
#RequestMapping(value = "/checkList", method = RequestMethod.POST, consumes="application/json",produces="application/json")
public ModelMap updateCheckList(#RequestBody CheckList checkList){
ModelMap modelMap = new ModelMap();
return modelMap;
}
}
CheckList class is as follows
import java.util.List;
public class CheckList {
String division;
String category;
String operation;
String transactionId;
String trackNumber;
String attentionReason;
String carNeedAttention;
String chargableDamage;
String missingItems;
String offences;
String outInAgentNumber;
List<MetaData> cList;
String outInCprNumber;
String outInDate;
String outInDuration;
String outInFuel;
String outInKm;
String outInRem1;
String outInRem2;
String outInRem3;
String userName;
String vehicleRetBy;
String updateMasterImage;
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTrackNumber() {
return trackNumber;
}
public void setTrackNumber(String trackNumber) {
this.trackNumber = trackNumber;
}
public String getAttentionReason() {
return attentionReason;
}
public void setAttentionReason(String attentionReason) {
this.attentionReason = attentionReason;
}
public String getCarNeedAttention() {
return carNeedAttention;
}
public void setCarNeedAttention(String carNeedAttention) {
this.carNeedAttention = carNeedAttention;
}
public String getChargableDamage() {
return chargableDamage;
}
public void setChargableDamage(String chargableDamage) {
this.chargableDamage = chargableDamage;
}
public String getMissingItems() {
return missingItems;
}
public void setMissingItems(String missingItems) {
this.missingItems = missingItems;
}
public String getOffences() {
return offences;
}
public void setOffences(String offences) {
this.offences = offences;
}
public List<MetaData> getcList() {
return cList;
}
public void setcList(List<MetaData> cList) {
this.cList = cList;
}
// public AccessoryList getAccessoryList() {
// return accessoryList;
// }
//
// public void setAccessoryList(AccessoryList accessoryList) {
// this.accessoryList = accessoryList;
// }
public String getOutInCprNumber() {
return outInCprNumber;
}
public void setOutInCprNumber(String outInCprNumber) {
this.outInCprNumber = outInCprNumber;
}
public String getOutInDate() {
return outInDate;
}
public void setOutInDate(String outInDate) {
this.outInDate = outInDate;
}
public String getOutInRem1() {
return outInRem1;
}
public void setOutInRem1(String outInRem1) {
this.outInRem1 = outInRem1;
}
public String getOutInRem2() {
return outInRem2;
}
public void setOutInRem2(String outInRem2) {
this.outInRem2 = outInRem2;
}
public String getOutInRem3() {
return outInRem3;
}
public void setOutInRem3(String outInRem3) {
this.outInRem3 = outInRem3;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getVehicleRetBy() {
return vehicleRetBy;
}
public void setVehicleRetBy(String vehicleRetBy) {
this.vehicleRetBy = vehicleRetBy;
}
public String getUpdateMasterImage() {
return updateMasterImage;
}
public void setUpdateMasterImage(String updateMasterImage) {
this.updateMasterImage = updateMasterImage;
}
public String getOutInAgentNumber() {
return outInAgentNumber;
}
public void setOutInAgentNumber(String outInAgentNumber) {
this.outInAgentNumber = outInAgentNumber;
}
public String getOutInDuration() {
return outInDuration;
}
public void setOutInDuration(String outInDuration) {
this.outInDuration = outInDuration;
}
public String getOutInFuel() {
return outInFuel;
}
public void setOutInFuel(String outInFuel) {
this.outInFuel = outInFuel;
}
public String getOutInKm() {
return outInKm;
}
public void setOutInKm(String outInKm) {
this.outInKm = outInKm;
}
}
MetaData is as folows
public class MetaData{
Integer id;
String label;
String uiComponent;
String featureType;
String value;
String comment;
String elementCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(int id)
{
this.id = id;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public String getUiComponent()
{
return uiComponent;
}
public void setUiComponent(String uiComponent)
{
this.uiComponent = uiComponent;
}
public String getFeatureType()
{
return featureType;
}
public void setFeatureType(String featureType)
{
this.featureType = featureType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getElementCode() {
return elementCode;
}
public void setElementCode(String elementCode) {
this.elementCode = elementCode;
}
}
But when i submitting the json request it is giving 415 unsuporrted media type error.
What is wrong with this code. Do anybody havve the answer. Thanks in advance.
Nothing with the code. You just need to make sure that Your POST request has the HTTP Content-Type header set to "application/json".
If you use curl to POST the data you can use the following parameter to set the header value:
curl -H "Content-Type:application/json"
Add an Accept header too:
curl -H "Content-Type:application/json" -H "Accept:application/json"

org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name

Hi i am working on a spring mvc application well i need to Serialize an object in order to pass it with an ajax Post.
my bean class :
#JsonSerialize(using = AgentSer.class)
public class AgentCust implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long personneID;
private String nom;
private String prenom;
private String matriculation;
private String marche;
private String compte;
private String phone, mail, chat;
public String getMarche() {
return marche;
}
public void setMarche(String marche) {
this.marche = marche;
}
public String getCompte() {
return compte;
}
public void setCompte(String compte) {
this.compte = compte;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getChat() {
return chat;
}
public void setChat(String chat) {
this.chat = chat;
}
public Long getPersonneID() {
return personneID;
}
public void setPersonneID(Long personneID) {
this.personneID = personneID;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getMatriculation() {
return matriculation;
}
public void setMatriculation(String matriculation) {
this.matriculation = matriculation;
}
}
and the class that will serialize my bean :
public class AgentSer extends JsonSerializer<AgentCust> {
#Override
public void serialize(AgentCust value, JsonGenerator jgen, SerializerProvider arg2) throws IOException, JsonProcessingException {
// TODO Auto-generated method stub
jgen.writeStartObject();
jgen.writeNumber(value.getPersonneID());
jgen.writeString(value.getMatriculation());
jgen.writeString(value.getNom());
jgen.writeString(value.getPrenom());
jgen.writeString(value.getCompte());
jgen.writeString(value.getMarche());
jgen.writeString(value.getChat());
jgen.writeString(value.getMail());
jgen.writeString(value.getPhone());
jgen.writeEndObject();
}
}
in my controller i use my class like that:
AgentCust ags ;
// i set values here .
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (Exception e) {
System.out.println(e);
}
but at the end i get that :
org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name
any help please.
Why are you using a custom serializer(which is wrong as it doesn't include the field names). You are really complicating your life.
You can set the serialization options like this (you can also set them in a static block):
final ObjectMapper mapper = new ObjectMapper();
/*
you can set them globally in a static block and reuse the mapper...
performance gain
*/
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
mapper.setSerializationInclusion(Include.NON_NULL);
The rest of the code is the same(just add a constructor in your AgentCust.class to avoid some mapping errors):
AgentCust ags = new AgentCust();
ags.setChat("chat1");
ags.setCompte("compte1");
ags.setMail("mail1");
ags.setMarche("marche1");
ags.setMatriculation("matriculation1");
ags.setNom("nom1");
ags.setPersonneID(123456L);
ags.setPhone("phone1");
ags.setPrenom("prenom1");
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
Another strange thing is that you're serializing the pojo as String. Why not JsonNode or ObjectNode?
public static ObjectNode convObjToONode(Object o) {
StringWriter stringify = new StringWriter();
ObjectNode objToONode = null;
try {
mapper.writeValue(stringify, o);
objToONode = (ObjectNode) mapper.readTree(stringify.toString());
} catch (JsonMappingException e) {
Logger.error("ERROR MAPPING JSON from object!", e);
} catch (JsonGenerationException e) {
Logger.error("ERROR GENERATING JSON from object!", e);
} catch (IOException e) {
Logger.error("ERROR IO when writing JSON from object!", e);
}
Logger.debug("Object as ObjectNode : " + objToONode);
return objToONode;
}

Store enums in database using hibernate

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.

How can I deseralize json object in java pojo class?

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.