[英]JAVA JACKSON: serialize a class with two field instead of all class
当外键调用实体时,我需要序列化只有两列的实体。 我在Wildfly工作,所以我正在寻找杰克逊解决方案。
假设我有实体类A.
public class A{
private Long id;
private String name;
private String anotherinfo;
private String foo;
...
}
和另一个B类:
public class B{
private Long id;
private String name;
private A parent;
}
当我搜索A时,我想用他的所有字段序列化A,但是当我需要检索B的istance时,我只需要两个字段(ID和标签)
如果我使用注释:
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@JsonIdentityReference(alwaysAsId=true)
private A parent;
我只会返回id。
我想要的结果将是:
B: {
"id" : 1,
"name" : "test",
"parent" : {
"id" : 1,
"name" : 2
}
}
您可以使用JsonIgnoreProperties批注来禁用序列化(和反序列化)的特定字段:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class B {
private Long id;
private String name;
@JsonIgnoreProperties({"anotherinfo", "foo"})
private A parent;
有A
扩展另一个类,比如C
:
class C {
Long id;
String name;
}
class A extends C {
String anotherinfo;
String foo;
...
}
然后,在B
:
class B {
Long id;
String name;
@JsonSerialize(as=C.class)
A parent;
}
序列化B
, parent
字段将只包含C
的字段,但在序列化A
对象的任何其他位置,您将看到A
和C
所有字段。
有关更多信息,请查看https://github.com/FasterXML/jackson-annotations#annotations-for-choosing-moreless-specific-types
解决了添加Json Serializer的问题。
我为父类创建了一个NationJsonSerializer:
public class NationJsonSerializer extends JsonSerializer<TNation> {
@Override
public void serialize(TNation value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.getId());
jgen.writeStringField("name", value.getComune());
jgen.writeStringField("iso", value.getCap());
jgen.writeEndObject();
}
}
然后,在城市课上,我把注释
@JoinColumn(name = "idtnation",referencedColumnName = "id",nullable = true)
@ManyToOne(targetEntity = TNation.class, fetch = FetchType.EAGER)
@JsonSerialize(using = NationJsonSerializer.class)
private TNation nation;
所以,如果我使用方法Nation n = getNation(long id); 我将收到所有列,但如果我使用getCity(),我将收到一个简化版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.