更新:我已經刪除了原來的代碼,因爲它只是混亂,只有簡化代碼需要在這裏。如果你想看到更多關於我在做什麼的細節,那就在編輯歷史中。傑克遜serialiazation與@JsonIdentityInfo不加身份信息沒有屬性反對
我有一個數據結構,我試圖與傑克遜序列化。這個結構中的一個項目是POJO,它的存在只是爲了促進參考它的不同項目之間的溝通。因此,重要的是他們持有相同的參考,而不是不同的參考。
問題是,儘管該類上有適當的@JsonIdentityInfo
註釋,但不會生成@id
屬性。如果我添加一個序列化屬性的類,然後@id
屬性生成就好了。但是我沒有想讓這個對象實際擁有的屬性:重點在於所有的實例都是共享的。有沒有什麼辦法可以強制傑克遜生成id屬性,儘管對象本身沒有屬性?
這裏有一個簡單的測試案例:
public class Test
{
@JsonTypeInfo(use=JsonTypeInfo.Id.MINIMAL_CLASS, include=JsonTypeInfo.As.PROPERTY)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public static class TestObject
{
}
public static void main (String [] args) throws JsonGenerationException, JsonMappingException, IOException
{
TestObject testObject = new TestObject();
new ObjectMapper()
.writerWithDefaultPrettyPrinter()
.writeValue (System.out, testObject);
}
}
運行該程序給出結果:
{
"@c" : ".Test$TestObject"
}
更改的TestObject類:
@JsonTypeInfo(use=JsonTypeInfo.Id.MINIMAL_CLASS, include=JsonTypeInfo.As.PROPERTY)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public static class TestObject
{
private int testProperty;
public int getTestProperty()
{
return testProperty;
}
public void setTestProperty (int testProperty)
{
this.testProperty = testProperty;
}
}
給出結果:
{
"@c" : ".Test$TestObject",
"@id" : 1,
"testProperty" : 0
}
這更接近我想要的東西,但我不希望「testProperty」產生。我如何擺脫它?如果我只是用@JsonIgnore
註釋它,我們回到第一個結果。