2017-10-04 107 views
-1

我有以下JSON:傑克遜反序列化陣列與空對象

{"beans":["{}",{"name":"Will"}]} 

和相應POJO類:

public class BeanA { 
    private BeanB[] beans; 
    ...getters/setters 
} 

public class BeanB { 
    private String name; 
    ...getters/setters 
} 

我想傑克遜反序列化到BeanA與BeanBs的陣列,所述第一個元素將只是BeanB的一個實例,第二個元素將是具有名稱屬性集的BeanB實例。

我已經序列化此創建的原始字符串:

BeanA beanA = new BeanA(); 
BeanB beanB = new BeanB(); 
beanB.setName("Will"); 
beanA.setBeans(new BeanB[] {new BeanB(), beanB}); 

這裏是我的objectMapper完整的配置:

this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); 
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); 

我得到的錯誤是這樣的:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `BeanB` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{}') 
+0

'「{}」'或'{}'? –

+0

JSON有一個混合內容的數組,其中第一個元素是一個字符串,第二個元素是一個對象。你的意思是'{「beans」:[{},{「name」:「Will」}]}',沒有'{}'的引號? – Andreas

+1

這裏有什麼問題? 'BeanA beanA = this.objectMapper.readValue(json,BeanA.class)'不工作嗎? –

回答

0

使用ObjectMapper#readValue

BeanA beanA = new BeanA(); 
BeanB beanB = new BeanB(); 
beanB.setName("Will"); 
beanA.setBeans(new BeanB[] {new BeanB(), beanB}); 

ObjectMapper om = new ObjectMapper(); 
om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); 
String json = om.writeValueAsString(beanA); 
System.out.println(json); 
// output: {"beans":[{},{"name":"Will"}]} 

BeanA deserializedBeanA = om.readValue(json, BeanA.class); 
System.out.println(deserializedBeanA); 
// output: BeanA{beans=[BeanB{name='null'}, BeanB{name='Will'}]}