Jaxb: How to replace a class/binding in given object tree while unmarshalling

后端 未结 3 1468
不知归路
不知归路 2020-12-20 00:44

I have a given set of classes to unmarshall a xml into an object tree. Now I get a extended xml and want to replace one class in the object tree with an extended version.

3条回答
  •  生来不讨喜
    2020-12-20 01:19

    A similar topic is discussed here: JAXB inheritance, unmarshal to subclass of marshaled class

    With jackson 2.8.6 you can just write something like

    @Test
    public void readXmlToSelfDefinedPojo2() throws Exception {
    
        ObjectMapper mapper = new XmlMapper();
        ExtAdress pojo = mapper.readValue(
                        Thread.currentThread().getContextClassLoader().getResourceAsStream("52109685.xml"),
                        ExtAdress.class);
        System.out.println(toString(pojo));
    }
    
    public String toString(Object obj) throws JsonGenerationException, JsonMappingException, IOException{
        StringWriter w = new StringWriter();
        new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
        return w.toString();
    }
    

    It will print

    {
      "systemId" : "on the 4",
      "type" : "test"
    }
    

    for

    
      
    on the 4
    give me some more
    test
    
        James
        Brown
        
    Funky Town HOME

    and

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class ExtAdress extends Adress {
        public String type;
        public ExtAdress() {
        }
    }
    

    and

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Adress {
        public String systemId;
    
        public Adress() {
        }
    }
    

提交回复
热议问题