我正在使用 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/