Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

java - Mapping JSON into POJO using Gson

I have the following JSON to represent the server response for a salt request:

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

And i tried to map it with the following 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;
        }
    }
}

Now everytime i do this:

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

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

The saltPojo.toString() is null. How can i map my JSON into POJO using Gson? Is the order of my variables important for the Gson mapping?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is the order of my variables important for the Gson mapping?

No, that's not the case.

How can i map my JSON into POJO using Gson?

It's Case Sensitive and the keys in JSON string should be same as variable names used in POJO class.

You can use @SerializedName annotation to use any variable name as your like.

Sample code:

  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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...