2016-02-17 44 views
2

我想寫類類型JSON解串器屬性寫傑克遜解串器,這樣,當類型是基於名稱給出JSON反序列化,將其映射值(類型接口,其)到其當前實現基於一些工廠方法根據名稱返回正確的類名,並填充剩餘的類,而不需要任何明確的反序列化,也不需要明確使用new創建TigerBeing或HumanBeing對象。如何基於JSON中

我試圖用@jsonCreator但我有整個HumanBeing或TigerBeing使用新的和通過了所有JSON在構造函數初始化。我需要進一步使用類型的自動映射,因爲pojo可能會非常複雜。

{type:[{ 
    "name": "Human", 
    "value": { 
     "height":6, 
     "weight":100, 
     "languages":["spanish","english"] 
    } 
}, 
{ 
"name":"Tiger", 
"value":{ 
    "extinct":1, 
    "found":["Asia", "America", "Europe", "Africa"] 
} 
} 
]} 

I have: 

public class Type { 
    String name; 
    Being value; 
} 

public interface Being { 
} 

public class TigerBeing implements Being { 
    Integer extinct; 
    String[] found; 
} 

public class HumanBeing implement Being { 
    Integer height; 
    Integer weight; 
    String[] languages; 
} 
+1

傑克遜具有用於多態類型的支持 - 請參見此處http://programmerbruce.blogspot.de/2011/05/deserialize-json-with-jackson-into.html - 實施例4是某物。你可以試試。該解決方案將要求你至少有一個類型屬性,在有效載荷有資格的有效載荷是一個''TigerBeing'or HumanBeing' –

回答

1
import java.io.IOException; 

public class BeingDeserializer extends JsonDeserializer<Being> { 

    @Override 
    public Expertise deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonMappingException { 

    JsonNode node = jp.getCodec().readTree(jp); 
    String beingName = node.get("name").asText(); 
    JsonNode valueNode = node.get("value"); 
    BeingName beingByName = ExpertiseName.getBeingByName(beingName); 
    if(beingByName ==null) { 
     throw new JsonMappingException("Invalid Being " + beingName); 
    } 

    Being being = JsonUtils.getObjectFromJsonNode(valueNode, 
      ExpertiseFactory.getExpertise(beingByName).getClass()); 
    return being; 
    } 
} 

這樣我就能夠解決上述問題。

+0

感謝,將嘗試了這一點。直到現在還在使用黑客。 – user3748525