如何将xml元素解析为基本类型?

时间:2016-05-23 08:48:54

标签: java xml jackson deserialization

我有这个xml:

<order>
    <id_address_delivery>4</id_address_delivery>
</order>

和java类

@JacksonXmlRootElement(localName = "order")
public static class Order
{
    @JacksonXmlProperty(localName = "id_address_delivery")
    public String id_address_delivery;
}

当我尝试用代码解析xml时:

XmlMapper XmlMapper = new XmlMapper()
XmlMapper.readValue(xml, Order.class);

我收到错误:无法从START_OBJECT令牌中反序列化java.lang.String的实例

如何纠正将xml元素反序列化为基本类型?

1 个答案:

答案 0 :(得分:1)

编辑:您能否确认变量&#34; cls&#34;是Order.class?如果cls是String.class,我会收到您报告的错误,但这不是正确的方法,因为您正在解析&lt; order&gt;元素不是&lt; id_address_delivery&gt;元件。

您是否有任何可能导致问题的定制配置?也许狡猾的空白 - 尝试完全删除空白?

我的代码......

public class Jackson {

    @JacksonXmlRootElement(localName = "order")
    private static class Order
    {
        @JacksonXmlProperty(localName = "id_address_delivery")
        public String id_address_delivery;
    }

    public static void main(String[] args) throws IOException {

        XmlMapper mapper = new XmlMapper();
        Order order = mapper.readValue("<order>\n\t<id_address_delivery>4</id_address_delivery></order>", Order.class);

        System.out.println(ToStringBuilder.reflectionToString(order, ToStringStyle.JSON_STYLE));
    }
}

产生

{&#34; id_address_delivery&#34;:&#34; 4&#34;}