简体   繁体   中英

How to map string json to POJO class?

I have a body return this:

{
  "a_name": "Max",
  "a_surname": "Miles",
  "a_details":  {
    "DETAILS": [
      {
        "DATE": "1996-12-31T00:00:00.000",
        "AGE": "24",
        "ACCNUM": "17",
        "FORSPEC": "Smth written here",
        "EXIT": "1"
      }, ] //list of json
  }

By now I am able to return name and surname, but having trouble mapping json field. Here is how my POJO looks like:

class Value {
    String name;
    String surname;
    List<AccountDetail> detail;

    //setter getter
}

class AccountDetail {
    LocalDateTime DATE;
    Number AGE;
    Number ACCNUM;
    String FORSPEC;
    Number EXIT;
    
    //setter getter
}

Here is a mapper for this field:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(
        DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<AccountDetails> details = mapper.readValue(stringJson, Value.class);

But I am getting errors like unrecognized fields and so on. What is a problem? Maybe I should realize my POJO class in other way or I have a problem with mapper?

You can used Gson library

   public class JsonFormater {

    public static void main(String[] args) {
        Gson gs = new Gson();
        // TODO Auto-generated method stub
        String jsonstring = "{\n" + "   \"a_name\":\"Max\",\n" + "   \"a_surname\":\"Miles\",\n"
                + "   \"a_details\":{\n" + "      \"DETAILS\":[\n" + "         {\n"
                + "            \"DATE\":\"1996-12-31T00:00:00.000\",\n" + "            \"AGE\":\"24\",\n"
                + "            \"ACCNUM\":\"17\",\n" + "            \"FORSPEC\":\"Smth written here\",\n"
                + "            \"EXIT\":\"1\"\n" + "         }\n" + "      ]\n" + "   }\n" + "}";

        Information infomation = gs.fromJson(jsonstring, Information.class);

        System.out.println(infomation.getaName());
        System.out.println(infomation.getaSurname());
        if (infomation.getaDetails() != null) {
            TestData testdata = infomation.getaDetails();
            for (Detail detail : testdata.getDetails()) {
                System.out.println(detail.getAge());
            }
        }

    }

}

public class Detail {
    @SerializedName("DATE")
    @Expose
    private String date;
    @SerializedName("AGE")
    @Expose
    private String age;
    @SerializedName("ACCNUM")
    @Expose
    private String accnum;
    @SerializedName("FORSPEC")
    @Expose
    private String forspec;
    @SerializedName("EXIT")
    @Expose
    private String exit;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getAccnum() {
        return accnum;
    }

    public void setAccnum(String accnum) {
        this.accnum = accnum;
    }

    public String getForspec() {
        return forspec;
    }

    public void setForspec(String forspec) {
        this.forspec = forspec;
    }

    public String getExit() {
        return exit;
    }

    public void setExit(String exit) {
        this.exit = exit;
    }

}

   public class TestData {

    @SerializedName("DETAILS")
    @Expose
    private List<Detail> details = null;

    public List<Detail> getDetails() {
        return details;
    }

    public void setDetails(List<Detail> details) {
        this.details = details;
    }

}

public class Information {
@SerializedName("a_name")
@Expose
private String aName;
@SerializedName("a_surname")
@Expose
private String aSurname;
@SerializedName("a_details")
@Expose
private TestData aDetails;

public String getaName() {
    return aName;
}

public void setaName(String aName) {
    this.aName = aName;
}

public String getaSurname() {
    return aSurname;
}

public void setaSurname(String aSurname) {
    this.aSurname = aSurname;
}

public TestData getaDetails() {
    return aDetails;
}

public void setaDetails(TestData aDetails) {
    this.aDetails = aDetails;
}

}

format your json correctly and try like this

You can use Jackson library for Json reading, and use annotation for different name @JsonProperty("a_name")

Few more issues I found in your code :

This is incorrect - List<AccountDetail> detail

You should declare a field DETAILS, as a new class, and inside should be the list.

Also "EXIT" field is missing in the class you defined.

Full working example.

public String test() throws JsonProcessingException
{
    String json = "your json here....";

    ObjectMapper mapper = new ObjectMapper();

    mapper.setDefaultPrettyPrinter(new PrettyPrinter());
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping();

    mapper.registerModule(new ParameterNamesModule())
    .registerModule(new Jdk8Module())
    .registerModule(new JavaTimeModule());

    mapper.readValue(json, Value.class);

    return "success";
}

public static class PrettyPrinter extends DefaultPrettyPrinter
{
    private static final long serialVersionUID = 1L;

    public PrettyPrinter()
    {
        indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
    }
}

private static class Value
{
    @JsonProperty("a_name")
    String name;
    @JsonProperty("a_surname")
    String surname;
    @JsonProperty("a_details")
    Details details;

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getSurname()
    {
        return surname;
    }
    public void setSurname(String surname)
    {
        this.surname = surname;
    }

    public Details getDetails()
    {
        return details;
    }

    public void setDetails(Details details)
    {
        this.details = details;
    }
}

private static class Details
{
    @JsonProperty("DETAILS")
    AccountDetail []detail;

    public AccountDetail[] getDetail()
    {
        return detail;
    }

    public void setDetail(AccountDetail[] detail)
    {
        this.detail = detail;
    }
}

private static class AccountDetail
{
    LocalDateTime DATE;
    Number AGE;
    Number ACCNUM;
    String FORSPEC;
    Number EXIT;

    public LocalDateTime getDATE()
    {
        return DATE;
    }

    public void setDATE(LocalDateTime DATE)
    {
        this.DATE = DATE;
    }

    public Number getAGE()
    {
        return AGE;
    }

    public void setAGE(Number AGE)
    {
        this.AGE = AGE;
    }

    public Number getACCNUM()
    {
        return ACCNUM;
    }

    public void setACCNUM(Number ACCNUM)
    {
        this.ACCNUM = ACCNUM;
    }

    public String getFORSPEC()
    {
        return FORSPEC;
    }

    public void setFORSPEC(String FORSPEC)
    {
        this.FORSPEC = FORSPEC;
    }

    public Number getEXIT()
    {
        return EXIT;
    }

    public void setEXIT(Number EXIT)
    {
        this.EXIT = EXIT;
    }
}

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