java - 使用Gson序列化公开字段时如何更改字段名称?

标签 java json gson

我正在使用 Gson 序列化 Java 对象并返回 json 字符串。该对象有很多字段,但我想特别返回 4 个字段。我使用 @Expose 注释告诉 Gson 忽略任何其他字段,但我也希望能够更改要返回的这些字段的名称。以这种方式使用 GsonBuilder

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

我只能获取带有 @Expose 的字段。有没有办法将 @SerializedName@Expose 一起使用,在返回这些字段之前更改它们的名称?使用这两个注释会阻止返回任何内容,但我还发现仅使用 @SerializedName 注释(并删除 .excludeFieldsWithoutExposeAnnotation())也会阻止这些字段被返回返回。

最佳答案

您走在正确的道路上。 这是一个有效的示例:

package test;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MyData {
  @Expose
  private String id;

  @Expose
  @SerializedName("fileOriginalName")
  private String myFilename;

  @Expose
  @SerializedName("fileOriginalPath")
  private String myPath;

  private String myName;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getMyFilename() {
    return myFilename;
  }

  public void setMyFilename(String myFilename) {
    this.myFilename = myFilename;
  }

  public String getMyPath() {
    return myPath;
  }

  public void setMyPath(String myPath) {
    this.myPath = myPath;
  }

  public String getMyName() {
    return myName;
  }

  public void setMyName(String myName) {
    this.myName = myName;
  }

}

调用者:

package test;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class Demo {
  static final Type MYDATA_TYPE = new TypeToken<MyData>() {
  }.getType();
  public static void main(String[] args){
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    MyData d = new MyData();

    d.setId("10");
    d.setMyFilename("was called myFilename");
    d.setMyName("should not be visible");
    d.setMyPath("was called myPath");

    String json = gson.toJson(d, MYDATA_TYPE);
    System.out.println(json);
  }
}

这是输出:

{
  "id": "10",
  "fileOriginalName": "was called myFilename",
  "fileOriginalPath": "was called myPath"
}

关于java - 使用Gson序列化公开字段时如何更改字段名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428997/

相关文章:

javascript - 无法在 Angular js 中绑定(bind)日历值

android - 无法合并 dex gradle 3.0.1

java - 使用 Jackson 将 Map 转换为 JSON

javascript - 如何在 Node 中使用 cheerio 和请求写入文件?

javascript - 将 JSON\n 转换为 HTML <br> 标记

java - 如何将 bean 对象放入 sessionMap,然后使用 Struts 2 属性标记在 jsp 页面上检索其属性

java - 更新 RecycleView 内的 Firestore 字段

json - 使用 GSON 的 JSON Java 对象给出计算器错误

java - 如何在 spring 中覆盖 JndiObjectFactoryBean 并在 java 中设置解密密码

java - 双击行时无法触发 MouseEvent