Java - 字段名称的别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33457640/
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-11-02 21:41:53  来源:igfitidea点击:

Java - Alias for Field Names

javagson

提问by userDSSR

Say I have an Object:

说我有一个对象:

Object A
    String field1 = "abc";
    String field2 = "xyz";

The json for the above is:

上面的json是:

{
    "ObjectA": {
      "field1": "abc",
      "field2": "xyz"
    }
}

I was trying to create a new id for the field names before sending the json. E.g. "field1" to be called "f1" and "field2" to be called "f2". So the intended output json is shown below:

在发送 json 之前,我试图为字段名称创建一个新的 id。例如,“field1”被称为“f1”,“field2”被称为“f2”。所以预期的输出 json 如下所示:

{
    "ObjectA": {
      "f1": "abc",
      "f2": "xyz"
    }
}

I am not sure how to do this. Can the above be done in a clean way? Thanks for your help and pointers.

我不知道该怎么做。以上可以以干净的方式完成吗?感谢您的帮助和指点。

I am using gson.

我正在使用 gson。

回答by Jesper Lehtinen

Use the annotation @SerializedName("name")on your fields. Like this:

@SerializedName("name")在您的字段上使用注释。像这样:

Object A
@SerializedName("f1")
String field1 = "abc";
@SerializedName("f2")
String field2 = "xyz";

See https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html.

请参阅https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html