I am trying to Convert following POJO to a JSON in @RestController
:
@Entity
@Table(name=\"user_location\")
@NamedQuery(name=\"UserLocation.findA
First remove that annotations from your State.java and City.java
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property="@id", scope = State.class)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property="@id", scope = City.class)
No need of these annotations and in RestController add return type as @ResponseBody UserLocation . It will give you json of that class.
This is how jackson designed JsonIdentityInfo annotation logic.
* Annotation used for indicating that values of annotated type
* or property should be serializing so that instances either
* contain additional object identifier (in addition actual object
* properties), or as a reference that consists of an object id
* that refers to a full serialization. In practice this is done
* by serializing the first instance as full object and object
* identity, and other references to the object as reference values.
Jackson will run the full serialization first time and only id will be serialized when it find that object second time.
So, there is two ways how you can fix it:
1) you can simple remove the @JsonIdentityInfo annotation and Jackson will serialize object as you expected but it will remove the @id field from the response. This is probably fine because you still will have 'id' property.
2) I feel like you can simply restructure your objects and delete some references. I would say it is good to do these changes anyway. First of all you can delete reference to the State from UserLocation. I would say that it is not necessary to have the State in userLocation class because of the State is attached to the City. By doing this you will access State from the City and your problem is solved. Also I would delete the reference to the list of userLocations from the City class as well as from State class.
It will look like:
UserLocation has City and doesn't have State.
City has State and doesn't have userLocations
State doesn't have userLocations as well as cities.
Hope this helps