简体   繁体   中英

JSON to GSON and POJO class

I have a JSON response like the following:

{
"number":"123456789101112",
"dimensions":"{\"height\":\"8.200\",\"width\":\"18.800\",\"depth\":\"9.400\"}",
"uom":"centimetre"
}

I am using the following to convert from JSON to GSON

Gson gson = new Gson();
Details details = gson.fromJson(JSONresponse, Details.class);

I want to know how to map the JSON response into my pojo class for converting this JSON to GSON and retrieving individual values.

I want to know how to access the height,width,depth from the response. This is my current Details class:

public class Details

{

private String number;

private String dimensions;

private String uom;

public void setNumber(String number){
    this.number = number;
}
public String getNumber(){
    return this.number;
}
public void setDimensions(String dimensions){
    this.dimensions = dimensions;
}
public String getDimensions(){
    return this.dimensions;
}
public void setUom(String uom){
    this.uom = uom;
}
public String getUom(){
    return this.uom;
}

}

I would model your POJO as:

public class Details {
    private Integer number;
    private Dimension dimensions;  // lowercase according to Java naming conventions
    private String uom;

    // getters and setters
}

public class Dimension {
    private String height;
    private String width;
    private String depth;

    // getters and setters
}

Then just use your current (correct) code, and then access whichever fields you want:

Gson gson = new Gson();
Details details = gson.fromJson(JSONresponse, Details.class);
String height = details.getDimensions().getHeight();

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