[英]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.