简体   繁体   中英

How to convert JSON object using GSON in Java?

Here is the JSON string return from API:

   {"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_image":"https:\/\/mydomain.com\/images\/eng\/promotion\/C199_MH.gif","error_message":{"eng":"","chi":""},"error_flags":""}

And I have created an object for this:

public class SummaryResponse {

    String bps_id;
    String bps_image;
    String bps_message;
    String as_of_date;
    String bp_earned;
    String bp_redeemed;
    String bp_balance;

    public String getBps_image() {
        return bps_image;
    }

    public LangResponse getBps_message() {
        return bps_message;
    }

    public String getAs_of_date() {
        return as_of_date;
    }

    public String getBp_earned() {
        return bp_earned;
    }

    public String getBp_redeemed() {
        return bp_redeemed;
    }

    public String getBp_balance() {
        return bp_balance;
    }
}

It does not convert as expert, as there is some JSON object inside the string, how to convert that as well? Thanks for helping.

You can create like this,

public class SummaryResponse {

    public String id;
    public String bps_id;

    public Summary summary;
    public Message bps_message;
    public String bps_image;
    public Message error_message;
    public String error_flags;

    class Summary {
        public String as_of_date;
        public int bp_earned;
        public String bp_balance;
        public String bp_redeemed;
    }

    class Message {
        public String eng;
        public String chi;
    }
}

you can call like this.

SummaryResponse summaryResponse = new Gson().fromJson([Your Json], SummaryResponse.class);  

This a quick simple way to parse an array of Objects and also a single object it works for me when I am parsing json.

I believe it will only work as long as the json object is well formatted. I haven't experimented with a ill-formatted json object but that is because the api it request from was build by me, so I haven't had to worry about that

        Gson gson = new Gson();
    SummaryResponse[] data = gson.fromJson(jsonObj, SummaryResponse[].class);

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