简体   繁体   中英

How to deserialize unwrapped json with Jackson?

I am using jackson for during JSON to java.It works fine normally.

However, I have a questions.

Most of my json will contain common fields like status and description along with few changing fields.

i was thinking of putting the common fields into a separate class and including its object into all classes but it does not work that way as Jackson was not able to understnad that these two fields need to be set in other object.

Class login {
    private String name;
    private Response response;
    /* getters and setters*/
}

Class Response {
    private String status;
    private string description;
    /* getters and setters*/
}

This will not work for json

{
    "name": "",
    "status": "",
    "description": ""
}

Kindly suggest the best way to achieve it.I can think of only inheritance to acchieve it.

Change your json like the following:

{
    "name": "",
    "response": {
        "status": "",
        "description": ""
    }
}

or if you cannot change JSON then change your class:

abstract class Response  
{  
  private String status;
  private String description;
}  


class Login extends Response  
{  
  private String name;
}  

The code you have now will only work if you change the json to the one I wrote above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM