简体   繁体   中英

How to map Json to Java object using jackson

I am using jackson to map json which I get from my post rest api to map to a java object.

the json is represent by

{
  "baseName": "xyz",
  "salary": [
    {
      "id": 1,
      "info": {
        "ename": "john",
        "eid": 143
      }
    },
    {
      "id": 2,
      "info": {
        "ename": "bg",
        "eid": 123
      }
    }
  ]
}

The java class are represent by

BaseInfo.java

class BaseInfo {
     String baseName;
     ArrayList<salary> salaries = new ArrayList<salary>();
}

Salary.java

class Salary {
    int id;
    EmplInfo emp;
}

EmplInfo.java

class EmplInfo{
    String ename;
    int eid;
}

But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc

You can use the JsonProperty annotation to rename properties

class BaseInfo {
    String baseName;
    @JsonProperty("salary")
    ArrayList<salary> salaries = new ArrayList<salary>();
}

class Salary {
    int id;
    @JsonProperty("info")
    EmplInfo emp;
}

Following are the solutions:

Either add JsonProperty annotations as specified by Michael or update json keys ie 'salary' to 'salaries' and 'info' to 'emp'

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