0

I have a Entity Order and which has a many to one relation to OrderType entity.

Order{
   OrderType type;
}

OrderType{
   int id;
   String tag; //This field is uniq
}

both are hibernate entities. When I serialise(using jackson) i am getting type as an object in order like

"type" : {
   "id":1,
   "tag" : "TEST"
}

But I would prefer to show my type as

"type" : "TEST"

Similarly while deserialising i need the OrderType object to be created even the type value will be string equivalent of it.

"type" : "TEST" should construct

{
   "id":1,
   "tag" : "TEST"
}

and which has to be an hibernate object mapped by unique field tag, And incase the string haven't present need to thrown an exception.

Can somebody suggest me the best way to achieve it.

amdixon
  • 3,814
  • 8
  • 25
  • 34
Ysak
  • 2,601
  • 6
  • 29
  • 53

3 Answers3

0

According to Jackson docs , you may try annotations to get your different json fields and ignore etc. Also similar question and answer is here like this situation.

Order{
   @JsonUnwrapped
   OrderType type;
}

OrderType{
   @JsonIgnore
   int id;
   @JsonProperty("type")
   String tag;
}

It should produce {"type":"typeValue"} when you serialized Order entity.

Community
  • 1
  • 1
İlker Korkut
  • 3,129
  • 3
  • 30
  • 51
  • But will it reproduce the id value from Database when I deserialise it – Ysak Oct 07 '15 at 10:13
  • @Ysak probably not , there is a similar approach http://stackoverflow.com/questions/12505141/only-using-jsonignore-during-serialization-but-not-deserialization but not on enum, may be you can wrap it an another class and then give JsonIgnore annotation getter only. – İlker Korkut Oct 07 '15 at 12:51
0

take a look at Jackson Custom Serializers and Deserializers. They are Jackson 2 features used to create custom serialization and deserialization object graph . See both articles here and here

Nikolay Rusev
  • 4,060
  • 3
  • 19
  • 29
0

Serializing: just add @JsonValue annotation to the OrderType.tag field (or getter method).

Deserializing: you can add a static @JsonCreator-annotated method:

public class OrderType {
   @JsonCreator public static OrderType fromJson(String tagText) {
   }
}

If you can easily get hold of the Hibernate session related to the current thread in this static method, then you can simply fill in the implementation to query for the order type.

araqnid
  • 127,052
  • 24
  • 157
  • 134