如何在不使用外部库的情况下使 toJson in Play 跳过模型中的某些字段?
How to make toJson in Play skip some fields in the model without using external libraries?
我正在尝试创建这样的实体
@Entity
public class Person extends Model {
@Id
public int id;
public String name;
}
然而,当我执行 toJson(person) 时,我的结果包含字段 id
和 name
。但我不想显示 id
。
是否有任何注释或其他东西(例如 gson 的 Expose)会使 toJson 跳过一些fields 以便最终的 json 输出不包含 id
字段??
[简答] - 使用@JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)
据我所知玩!使用不序列化瞬态字段的 Gson。
所以我想像这样添加 transient
修饰符:
@Id
public transient int id;
应该做。
您有两个选择:
首先,
如果您需要在不使用外部库的情况下跳过某些字段:
您可以在以下位置查看原始问题和答案:
您可以在该字段的 getter 方法上使用 Jackson 的 @JsonIgnore 注释,您会发现结果 JSON.
中没有这样的键值对
@JsonIgnore
public String name;
第二,如果您使用 Gson 库,其他方法很快来自@ChrisSeline:
Any fields you don't want to be serialized in general you should use
the "transient" modifier, and this also applies to JSON serializers
(at least it does to a few that I have used, including Gson).
If you don't want name to show up in the serialised JSON give it a
transient keyword, e.g.,
private transient String name;
在 gson 中,最简单的方法是添加 transient 作为
public transient int id;
或者您可以添加注释 @Expose 和
new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
实现它
我正在尝试创建这样的实体
@Entity
public class Person extends Model {
@Id
public int id;
public String name;
}
然而,当我执行 toJson(person) 时,我的结果包含字段 id
和 name
。但我不想显示 id
。
是否有任何注释或其他东西(例如 gson 的 Expose)会使 toJson 跳过一些fields 以便最终的 json 输出不包含 id
字段??
[简答] - 使用@JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)
据我所知玩!使用不序列化瞬态字段的 Gson。
所以我想像这样添加 transient
修饰符:
@Id
public transient int id;
应该做。
您有两个选择:
首先, 如果您需要在不使用外部库的情况下跳过某些字段: 您可以在以下位置查看原始问题和答案:
您可以在该字段的 getter 方法上使用 Jackson 的 @JsonIgnore 注释,您会发现结果 JSON.
中没有这样的键值对@JsonIgnore
public String name;
第二,如果您使用 Gson 库,其他方法很快来自@ChrisSeline:
Any fields you don't want to be serialized in general you should use the "transient" modifier, and this also applies to JSON serializers (at least it does to a few that I have used, including Gson).
If you don't want name to show up in the serialised JSON give it a transient keyword, e.g.,
private transient String name;
在 gson 中,最简单的方法是添加 transient 作为
public transient int id;
或者您可以添加注释 @Expose 和
new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
实现它