Read embedded object in Jackson

前端 未结 3 1017
一整个雨季
一整个雨季 2020-12-14 08:27

I\'m trying to read a legacy JSON code using Jackson 2.0-RC3, however I\'m stuck with an \"embedded\" object.

Given a following JSON:

{
    \"title\"         


        
3条回答
  •  死守一世寂寞
    2020-12-14 09:22

    I would deserialize the original JSON to a single, flat object first (kind of like an adapter), then create your own domain objects.

    class ItemLegacy {
        private String title;
    
        @JsonProperty("date")
        private Date createdAt;
    
        @JsonPropery("author")
        private String name;
    
        @JsonPropery("author_avatar")
        private URL avatar;
    
        @JsonProperty("author_group")
        private Integer group;
    
        @JsonProperty("author_prop")
        private Integer group;
    }
    

    Then use this object to fill out your Item and Author objects and create the correct relationships.

     //... the deserialized original JSON
     ItemLegacy legacy ...
    
     // create an author
     Author author = new Author();
     author.setName(legacy.getName());
     author.setGroup(legacy.getGroup());
     ...
    
     // create an item
     Item item = new Item();
     item.setTitle(legacy.getTitle());
     ...
    
     // finally set the author... and you should have the desired structure
     item.setAuthor(author);
    

    Your Item class could only be automatically deserialized from the following form:

    {
        "title": "Hello world!",
        "date": "2012-02-02 12:23:34".
        "author": { 
                    "name": "username", 
                    "author_avatar": "http://...", 
                    "author_group": "123", 
                    "author_prop": "value" 
                  }
    }
    

    You might be able to do something with custom deserialization, but it would not be the simpler solution for sure.

提交回复
热议问题