2012-04-26 66 views
18

現在我正在和Jackson合作,並且我對它有一些疑問。Json反序列化到使用Jackson的另一個類層次結構

首先。我有兩種服務,一種是數據收集和發送服務,另一種是接收這些數據,例如,將其記錄到文件中。

所以,第一個服務類層次結構是這樣的:

  +----ConcreteC 
     | 
Base ----+----ConcreteA 
     | 
     +----ConcreteB 

和第二服務具有類層次結構是這樣的:

ConcreteAAdapter extends ConcreteA implements Adapter {} 
ConcreteBAdapter extends ConcreteB implements Adapter {} 
ConcreteCAdapter extends ConcreteC implements Adapter {} 

,第一業務一無所知ConcreteXAdapter

的方法,我發送的第一服務的數據:

Collection<Base> data = new LinkedBlockingQueue<Base>() 
JacksonUtils utils = new JacksonUtils(); 
data.add(new ConcreteA()); 
data.add(new ConcreteB()); 
data.add(new ConcreteC()); 
... 
send(utils.marshall(data)); 
... 

public class JacksonUtils { 

    public byte[] marshall(Collection<Base> data) throws IOException { 
     ByteArrayOutputStream out = new ByteArrayOutputStream() { 
      @Override 
      public byte[] toByteArray() { 
       return buf; 
      } 
     }; 

     getObjectMapper().writeValue(out, data); 
     return out.toByteArray(); 
    } 
    protected ObjectMapper getObjectMapper() { 
     return new ObjectMapper(); 
    } 

    public Object unmarshall(byte[] json) throws IOException { 
     return getObjectMapper().readValue(json, Object.class); 
    } 

    public <T> T unmarshall(InputStream source, TypeReference<T> typeReference) throws IOException { 
     return getObjectMapper().readValue(source, typeReference); 
    } 

    public <T> T unmarshall(byte[] json, TypeReference<T> typeReference) throws IOException { 
     return getObjectMapper().readValue(json, typeReference); 
    } 
} 

所以,我想desirialize JSON到收藏ConcreteXAdapter,不進的ConcreteXConcreteA -> ConcreteAAdapter, ConcreteB -> ConcreteBAdapter, ConcreteC -> ConcreteCAdapter)系列。在我描述的情況下,我想得到:

Collection [ConcreteAAdapter, ConcreteBAdapter, ConcreteCAdapter] 

我該怎麼做?

回答

15

我是如何解決這個問題的。下面是一個例子項目的類圖: class diagram

所以我想反序列化後得到ConcreteAAdapter形式ConcreteA

我的解決方案是擴展ClassNameIdResolver以添加將基類對象反序列化爲子類類對象(子類類不增加額外的功能和附加字段)的功能。

這裏是一個反序列化創建ObjectMapper代碼:

protected ObjectMapper getObjectMapperForDeserialization() { 
     ObjectMapper mapper = new ObjectMapper(); 

     StdTypeResolverBuilder typeResolverBuilder = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 
     typeResolverBuilder = typeResolverBuilder.inclusion(JsonTypeInfo.As.PROPERTY); 
     typeResolverBuilder.init(JsonTypeInfo.Id.CLASS, new ClassNameIdResolver(SimpleType.construct(Base.class), TypeFactory.defaultInstance()) { 
      private HashMap<Class, Class> classes = new HashMap<Class, Class>() { 
       { 
        put(ConcreteA.class, ConcreteAAdapter.class); 
        put(ConcreteB.class, ConcreteBAdapter.class); 
        put(ConcreteC.class, ConcreteCAdapter.class); 
       } 
      }; 

      @Override 
      public String idFromValue(Object value) { 
       return (classes.containsKey(value.getClass())) ? value.getClass().getName() : null; 
      } 

      @Override 
      public JavaType typeFromId(String id) { 
       try { 
        return classes.get(Class.forName(id)) == null ? super.typeFromId(id) : _typeFactory.constructSpecializedType(_baseType, classes.get(Class.forName(id))); 
       } catch (ClassNotFoundException e) { 
        // todo catch the e 
       } 
       return super.typeFromId(id); 
      } 
     }); 
     mapper.setDefaultTyping(typeResolverBuilder); 
     return mapper; 
    } 

這裏是序列化創建ObjectMapper代碼:

protected ObjectMapper getObjectMapperForSerialization() { 
    ObjectMapper mapper = new ObjectMapper(); 

    StdTypeResolverBuilder typeResolverBuilder = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 
    typeResolverBuilder = typeResolverBuilder.inclusion(JsonTypeInfo.As.PROPERTY); 
    typeResolverBuilder.init(JsonTypeInfo.Id.CLASS, new ClassNameIdResolver(SimpleType.construct(Base.class), TypeFactory.defaultInstance())); 
    mapper.setDefaultTyping(typeResolverBuilder); 

    return mapper; 
} 

測試代碼:

public static void main(String[] args) throws IOException { 
    JacksonUtils JacksonUtils = new JacksonUtilsImpl(); 

    Collection<Base> data = new LinkedBlockingQueue<Base>(); 
    data.add(new ConcreteA()); 
    data.add(new ConcreteB()); 
    data.add(new ConcreteC()); 

    String json = JacksonUtils.marshallIntoString(data); 

    System.out.println(json); 

    Collection<? extends Adapter> adapters = JacksonUtils.unmarshall(json, new TypeReference<ArrayList<Adapter>>() {}); 

    for (Adapter adapter : adapters) { 
     System.out.println(adapter.getClass().getName()); 
    } 
} 

全部JacksonUtils類的代碼:

public class JacksonUtilsImpl implements JacksonUtils { 

    @Override 
    public byte[] marshall(Collection<Base> data) throws IOException { 
     ByteArrayOutputStream out = new ByteArrayOutputStream() { 
      @Override 
      public byte[] toByteArray() { 
       return buf; 
      } 
     }; 

     getObjectMapperForSerialization().writerWithType(new TypeReference<Collection<Base>>() {}).writeValue(out, data); 
     return out.toByteArray(); 
    } 

    @Override 
    public String marshallIntoString(Collection<Base> data) throws IOException { 
     return getObjectMapperForSerialization().writeValueAsString(data); 
    } 

    protected ObjectMapper getObjectMapperForSerialization() { 
     ObjectMapper mapper = new ObjectMapper(); 

     StdTypeResolverBuilder typeResolverBuilder = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 
     typeResolverBuilder = typeResolverBuilder.inclusion(JsonTypeInfo.As.PROPERTY); 
     typeResolverBuilder.init(JsonTypeInfo.Id.CLASS, new ClassNameIdResolver(SimpleType.construct(Base.class), TypeFactory.defaultInstance())); 
     mapper.setDefaultTyping(typeResolverBuilder); 

     return mapper; 
    } 

    protected ObjectMapper getObjectMapperForDeserialization() { 
     ObjectMapper mapper = new ObjectMapper(); 

     StdTypeResolverBuilder typeResolverBuilder = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 
     typeResolverBuilder = typeResolverBuilder.inclusion(JsonTypeInfo.As.PROPERTY); 
     typeResolverBuilder.init(JsonTypeInfo.Id.CLASS, new ClassNameIdResolver(SimpleType.construct(Base.class), TypeFactory.defaultInstance()) { 
      private HashMap<Class, Class> classes = new HashMap<Class, Class>() { 
       { 
        put(ConcreteA.class, ConcreteAAdapter.class); 
        put(ConcreteB.class, ConcreteBAdapter.class); 
        put(ConcreteC.class, ConcreteCAdapter.class); 
       } 
      }; 

      @Override 
      public String idFromValue(Object value) { 
       return (classes.containsKey(value.getClass())) ? value.getClass().getName() : null; 
      } 

      @Override 
      public JavaType typeFromId(String id) { 
       try { 
        return classes.get(Class.forName(id)) == null ? super.typeFromId(id) : _typeFactory.constructSpecializedType(_baseType, classes.get(Class.forName(id))); 
       } catch (ClassNotFoundException e) { 
        // todo catch the e 
       } 
       return super.typeFromId(id); 
      } 
     }); 
     mapper.setDefaultTyping(typeResolverBuilder); 
     return mapper; 
    } 

    @Override 
    public Object unmarshall(byte[] json) throws IOException { 
     return getObjectMapperForDeserialization().readValue(json, Object.class); 
    } 

    @Override 
    public <T> T unmarshall(InputStream source, TypeReference<T> typeReference) throws IOException { 
     return getObjectMapperForDeserialization().readValue(source, typeReference); 
    } 

    @Override 
    public <T> T unmarshall(byte[] json, TypeReference<T> typeReference) throws IOException { 
     return getObjectMapperForDeserialization().readValue(json, typeReference); 
    } 

    @Override 
    public <T> Collection<? extends T> unmarshall(String json, Class<? extends Collection<? extends T>> klass) throws IOException { 
     return getObjectMapperForDeserialization().readValue(json, klass); 
    } 


    @Override 
    public <T> Collection<? extends T> unmarshall(String json, TypeReference typeReference) throws IOException { 
     return getObjectMapperForDeserialization().readValue(json, typeReference); 
    } 
} 
27

爲此,你需要通過額外的信息在JSON:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, 
     include=JsonTypeInfo.As.PROPERTY, property="@type") 
class Base { 
... 
} 

然後在序列化會加重@type領域:

objectMapper.registerSubtypes(
      new NamedType(ConcreteAAdapter.class, "ConcreteA"), 
      new NamedType(ConcreteBAdapter.class, "ConcreteB"), 
      new NamedType(ConcreteCAdapter.class, "ConcreteC") 
      ); 

// note, that for lists you need to pass TypeReference explicitly 
objectMapper.writerWithType(new TypeReference<List<Base>>() {}) 
    .writeValueAsString(someList); 


    { 
     "@type" : "ConcreteA", 
     ... 
    } 

上反序列化將是:

objectMapper.registerSubtypes(
      new NamedType(ConcreteA.class, "ConcreteA"), 
      new NamedType(ConcreteB.class, "ConcreteB"), 
      new NamedType(ConcreteC.class, "ConcreteC") 
      ); 
    objectMapper.readValue(....) 

更多這裏:http://wiki.fasterxml.com/JacksonPolymorphicDeserialization

+0

感謝您的快速回復!我更新了這個問題。簡而言之,第一個服務對「ConcreteXAdapter」一無所知。所以問題是如果傑克遜在JSON中發現了'ConcreteX',那麼如何告訴Jackson創建'ConcreteXAdapter'。 – pbespechnyi 2012-04-26 20:20:13

+1

在這種情況下,我會建議手動傳遞類型(如「@type」:「ConcreteA」),然後根據屬性反序列化另一端。即您需要爲此實現自定義序列化程序。 – 2012-04-26 20:29:46

+0

所以沒有辦法做到這一點開箱即用。好的,謝謝你的幫助! – pbespechnyi 2012-04-26 20:37:14

9

我發現程序員的方法是最清晰和最容易工作的(下面的例子)。 我從他的回答中的信息來一個相關的問題: https://stackoverflow.com/a/6339600/1148030 和相關的博客文章: http://programmerbruce.blogspot.fi/2011/05/deserialize-json-with-jackson-into.html

還檢查了這個友好的wiki頁面(尤金Retunsky的答案也提到): http://wiki.fasterxml.com/JacksonPolymorphicDeserialization

另外一個不錯的維基頁面:http://wiki.fasterxml.com/JacksonMixInAnnotations

下面是一個簡單的例子,讓您的想法:

配置ObjectMapper這樣的:(容易定義爲一個內部類)

mapper.getDeserializationConfig().addMixInAnnotations(Base.class, BaseMixin.class); 
    mapper.getSerializationConfig().addMixInAnnotations(Base.class, BaseMixin.class); 

例BaseMixin類

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type") 
@JsonSubTypes({ 
    @JsonSubTypes.Type(value=ConcreteA.class, name="ConcreteA"), 
    @JsonSubTypes.Type(value=ConcreteB.class, name="ConcreteB") 
}) 
private static class BaseMixin { 
} 

在第二服務可以定義像這樣的BaseMixin:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type") 
@JsonSubTypes({ 
    @JsonSubTypes.Type(value=ConcreteAAdapter.class, name="ConcreteA"), 
    @JsonSubTypes.Type(value=ConcreteBAdapter.class, name="ConcreteB") 
}) 
private static class BaseMixin { 
} 
+0

您的解決方案對於第一次看起來更乾淨和正確。現在我不能說它適合我,因爲它很久以前。但無論如何謝謝你的答案! – pbespechnyi 2012-12-22 22:35:39

相關問題