简体   繁体   English

如何在Java中使用GSON转换JSON对象?

[英]How to convert JSON object using GSON in Java?

Here is the JSON string return from API: 这是从API返回的JSON字符串:

   {"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? 它不会转换为专家,因为字符串中有一些JSON对象,也该如何转换呢? 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. 这是一种解析对象数组的快速简便方法,也是解析json时对我有用的单个对象。

I believe it will only work as long as the json object is well formatted. 我相信,只要json对象格式正确,它就只能工作。 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 我没有尝试过格式错误的json对象,但这是因为它请求的api是我自己构建的,因此我不必担心

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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