Convert Entity object to JSON

后端 未结 2 1109
囚心锁ツ
囚心锁ツ 2021-01-22 22:44

I need to convert entity object to json. I put


    

        
相关标签:
2条回答
  • 2021-01-22 23:21

    @RequestMapping(produces="application/json") is what you need and DO NOT FORGET to make a POST request in your JS code (not GET).

    0 讨论(0)
  • 2021-01-22 23:25

    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

    0 讨论(0)
提交回复
热议问题