2016-04-18 163 views
3

我需要使用外鍵序列化只有兩列的實體。我在Wildfly工作,所以我正在尋找傑克遜解決方案。JAVA JACKSON:使用兩個字段而不是所有類序列化一個類

假設我有實體的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; 
} 

我想序列化與他的所有領域,當我搜索了,但是當我需要找回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 
    } 
} 
+0

對字段使用關鍵字transient並且它們不會被序列化。 – LearningPhase

+0

http://stackoverflow.com/questions/8179986/jackson-change-jsonignore-dynamically –

+0

瞬態關鍵字可能對此有所幫助。 –

回答

1

解決了添加JSON序列。

我已經創建了一個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; 

所以,如果我用的方法民族N = getNation (長ID);我會收到所有列,但如果我使用getCity(),我會收到一個簡化版本。

1

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對象時,您將看到來自AC的所有字段。

欲瞭解更多信息,看看https://github.com/FasterXML/jackson-annotations#annotations-for-choosing-moreless-specific-types

+0

我不能使用這個解決方案,因爲我有一個明確的繼承策略,使用抽象類和標準化方法 –

+0

@DanieleLicitra C也可以是一個接口與getProperty()Bean風格的方法和由A實施(對實現的接口沒有限制。) 因此,如果您對A具有源代碼控制權,那麼與自定義序列化程序相比,我發現此解決方案更容易,樣板更少。 – Piohen

2

可以使用JsonIgnoreProperties註釋,以禁用序列化(和反序列化)具體領域:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 

public class B { 
    private Long id; 
    private String name; 

    @JsonIgnoreProperties({"anotherinfo", "foo"}) 
    private A parent; 
+2

如果忽略屬性的集合不隨時間變化,這很好。 但是,如果人們期望可能有更多屬性需要忽略,這可能會產生問題,因爲在A中添加新字段意味着將忽略的列表擴展到其他文件中。 我發現解決方案宣佈明確的字段列表序列化更好,因爲這一點。 但是,如果這組屬性是固定的,這沒關係。 – Piohen

相關問題