Java 使用Gson在Android中@SerializedName注解的基本目的是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28957285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:05:34  来源:igfitidea点击:

What is the basic purpose of @SerializedName annotation in Android using Gson

javaandroidjsongson

提问by Muhammad Ali

What is the basic purpose of @SerializedNameannotation in Android using Gson?

@SerializedName使用 Gson 在 Android 中进行注释的基本目的是什么?

Give me some different examples. I can't understand the main purpose of using it.

给我一些不同的例子。我无法理解使用它的主要目的。

回答by Chintan Rathod

Java class example,

Java类示例,

public class Person {

    @SerializedName("name")
    private String personName;

    @SerializedName("bd")
    private String birthDate;

}

This class has two fields that represent the person name and birth date of a person. These fields are annotated with the @SerializedNameannotation. The parameter (value) of this annotation is the name to be used when serialisingand deserialisingobjects. For example, the Java field personNameis represented as namein JSON.

这个类有两个字段,分别代表一个人的姓名和出生日期。这些字段使用@SerializedName注释进行注释。该注解的参数(值)是 whenserialisingdeserialisingobjects要使用的名称。例如,Java 字段personName在 JSON 中表示为name

JSON Example,

JSON 示例,

{
    "name":"chintan",
    "bd":"01-01-1990"
}

回答by Sandip Fichadiya

There are already few answers here,but I would like to add that if you are using ProGuardto Obfuscate your code & don't use @SerializedName("name")in your model class, then your GSON won't work. Because due to obfuscation, your variable names might have changed from String nameto String aresulting into broken GSON parsing as GSON will look for key ainto json & it will fail.

这里已经有几个答案,但我想补充一点,如果您使用ProGuard混淆代码并且不在@SerializedName("name")模型类中使用,那么您的 GSON 将无法工作。因为由于混淆,您的变量名称可能已从 更改String nameString a导致 GSON 解析损坏,因为 GSON 将查找ajson 中的密钥并且它会失败。

By specifying @SerializedName, GSON will not look in json based on variable name & will just use specified @SerializedName.

通过指定@SerializedName,GSON 将不会根据变量名称在 json 中查找,而只会使用指定的@SerializedName.

Of Course you can tell proguard to not obfuscate your model, but if you would like to have model obfuscated, then you must specify @SerializedName

当然你可以告诉 proguard 不要混淆你的模型,但是如果你想混淆模型,那么你必须指定 @SerializedName

回答by Alankar Gupta

You can instruct Proguard to not obfuscate your data classes by specifying @Keep on top of the class. This will neither remove nor obfuscate your class. No need to add @SerializedName to each and every field explicitly if the field name is similar to the Json key being used for it.

您可以通过在类的顶部指定 @Keep 来指示 Proguard 不要混淆您的数据类。这既不会删除也不会混淆你的类。如果字段名称与用于它的 Json 键相似,则无需将 @SerializedName 显式添加到每个字段。