I need to convert entity object to json. I put
@RequestMapping(produces="application/json")
is what you need and DO NOT FORGET to make a POST request in your JS code (not GET).
If your object joined other table then you can only do this in the following way.
First, let’s annotate the relationship with @JsonManagedReference, @JsonBackReference to allow Jackson to better handle the relation:
Here’s the “User” entity:
public class User {
public int id;
public String name;
@JsonBackReference
public List<Item> userItems;
}
And the “Item“:
public class Item {
public int id;
public String itemName;
@JsonManagedReference
public User owner;
}
Let’s now test out the new entities:
@Test
public void
givenBidirectionRelation_whenUsingJacksonReferenceAnnotation_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
Here is the output of serialization:
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John"
}
}
Note that:
@JsonManagedReference is the forward part of reference – the one that gets serialized normally. @JsonBackReference is the back part of reference – it will be omitted from serialization.
Quoted from the link below. You can visit for more.
Jackson – Bidirectional Relationships