简体   繁体   中英

Unable to deserialize non formatted child node in XML with Jackson

I am converting Xml to Pojo object with help of jackson, But due to different format of xml it's not converting all fields to Pojo, Please follow for xml structure and mapping Pojo,

Here I want to deserialize 13 value of iphone.

XML- <PhoneDetails> <Iphone os="ios">13</Iphone> </PhoneDetails>

POJO

@lombok.Data 
public class PhoneDetails { 
    @JacksonXmlProperty(localName = "Iphone") 
    private Iphone iphoneDetails; 
}

@lombok.Data 
public class Iphone { 
    private String os; 
    private String iphone; 
}

main method

public class Demo { 
    public static void main(String[] args) throws Exception { 
        XmlMapper xmlMapper = new XmlMapper();      
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
        xmlMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        xmlMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, false); 
        File availsContract = ResourceUtils.getFile("classpath:to_deserialize.xml");

        String content = new String(Files.readAllBytes(availsContract.toPath()));
        PhoneDetails productDetail = xmlMapper.readValue(content, PhoneDetails.class);
        System.out.println("Product Details :" + productDetail);
    }

}

Please reply with solutions.

Welcome to Stack Overflow, a simple xmlMapper mapper is enough to deserialize your xml; you have to use the JacksonXmlText annotation to deserialize the 13 value from the <PhoneDetails> <Iphone os="ios">13</Iphone> </PhoneDetails> xml file into your String iphone property:

@Data
public class PhoneDetails { 
   
    @JacksonXmlProperty(localName = "Iphone") 
    private Iphone iphoneDetails; 
}

@Data
public class Iphone {

    private String os;
    @JacksonXmlText
    private String iphone;
}

//Input xmlfile:
//<PhoneDetails> <Iphone os="ios">13</Iphone> </PhoneDetails>
XmlMapper xmlMapper = new XmlMapper();
PhoneDetails phoneDetails = xmlMapper.readValue(xml, PhoneDetails.class);
//ok, it prints PhoneDetails(iphoneDetails=Iphone(os=ios, iphone=13))
System.out.print(phoneDetails);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM