使用Gson将JSON映射到POJO

时间:2014-11-20 12:21:24

标签: java json gson

我有以下JSON来表示salt请求的服务器响应:

{
    "USER":
    {
        "E_MAIL":"email",
        "SALT":"salt"
    },
    "CODE":"010"
}

我试图将它映射到以下POJO:

public class SaltPOJO {
    private String code = null;
    private User user = null;

    @Override
    public String toString() {
        return this.user.toString();
    }

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    public class User {
        private String e_mail = null;
        private String salt = null;

        @Override
        public String toString() {
            return this.e_mail + ": " + this.salt;
        }
        public String getE_mail() {
            return e_mail;
        }
        public void setE_mail(String e_mail) {
            this.e_mail = e_mail;
        }
        public String getSalt() {
            return salt;
        }
        public void setSalt(String salt) {
            this.salt = salt;
        }
    }
}

现在我每次都这样做:

Gson gson = new Gson();
SaltPOJO saltPojo = gson.fromJson(json.toString(), SaltPOJO.class);

Log.v("Bla", saltPojo.toString());

saltPojo.toString()为空。如何使用Gson将我的JSON映射到POJO? 我的变量的顺序对Gson映射很重要吗?

2 个答案:

答案 0 :(得分:15)

  

我的变量的顺序对于Gson映射是否重要?

不,事实并非如此。

  

如何使用Gson将我的JSON映射到POJO?

区分大小写,JSON字符串中的键应与POJO类中使用的变量名相同。

您可以使用@SerializedName注释来使用任何变量名称。

示例代码:

  class SaltPOJO {
        @SerializedName("CODE")
        private String code = null;
        @SerializedName("USER")
        private User user = null;
        ...

        class User {
            @SerializedName("E_MAIL")
            private String e_mail = null;
            @SerializedName("SALT")
            private String salt = null;

答案 1 :(得分:0)

您的getter和setter之间没有正确的映射。如果你将你的json更改为如下所示,它将起作用:

{
    "user":
    {
        "email":"email",
        "salt":"salt"
    },
    "code":"010"
}

如果你正在获得第三方json,那么不幸的是,你必须改变你的pojo或者你可以使用适配器。

相关问题