关于gson,@Expose@SerializedName("stringValue")的区别是什么?

推荐答案

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字符串如下

{
    "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字符串如下

{
    "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();

低于userName的不会被反序列化.用户名的值将为null.

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

低于userName将不会被序列化.

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

Json字符串如下. Only userAge will be deserialized.

{
    "age":30
}

Json相关问答推荐

使用Jolt库对多个数组进行嵌套循环

数据到jsonObject到数据到 struct 是可能的吗?

Oracle JSON 查询中的动态列列表

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

如何在 terraform 输出中打印一组用户信息

我需要在 mongodb compass 中检索索引(编号 1)信息

JOLT 在 struct 体中间添加一个 JSON 字段

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

Powershell 无法从名为 count 的键中获取价值

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

如何一次加载无限滚动中的所有条目以解析python中的HTML

python,将Json写入文件

反序列化大型 json 对象的 JsonMaxLength 异常

按 JSON 数据类型 postgres 排序

如何使用 C# 将 JSON 文本转换为对象

如何在 django rest 框架中定义列表字段?

JSON对象中的JavaScript递归搜索

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

如何使用 Javascript 将数据写入 JSON 文件

如何使用 Gson 将 JSONArray 转换为 List?