Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Gson: @Expose vs @SerializedName

With respect to Gson what is the difference between @Expose and @SerializedName("stringValue")?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Even if it's late I wanted to answer this question. To explain it we must know what is serialization and deserialization. serialization is converting object into json string and deserialization is converting json string into object.

Let's say we've User class with no annotations.

public class User{
    private String userName;
    private Integer userAge;

    public User(String name, Integer age){
        userName = name;
        userAge = age;
    }
}

And we serialize this object as below

User user = new User("Ahmed", 30);
Gson gson = new Gson();
String jsonString = gson.toJson(user);

Json string will be like this

{
    "userName":"Ahmed",
    "userAge":30
}

If we add annotation @SerializedName

public class User{

    @SerializedName("name")
    private String userName;
    @SerializedName("age")
    private Integer userAge;

    public User(String name, Integer age){
        userName = name;
        userAge = age;
    }
}

Json string will be like this

{
    "name":"Ahmed",
    "age":30
}

@Expose is used to allow or disallow serialization and deserialization. @Expose is optional and it has two configuration parameters: serialize and deserialize. By default they're set to true. To serialize and deserialize with @Expose we create gson object like this

Gson gsonBuilder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

Below userName won't be deserialized. userName's value will be null.

@SerializedName("name")
@Expose(deserialize = false)
private String userName;

Below userName won't be serialized.

@SerializedName("name")
@Expose(serialize = false)
private String userName;

Json string will be like this. Only userAge will be deserialized.

{
    "age":30
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...