Unmarshall与JAXB不起作用 [英] Unmarshall with JAXB doesn't work

查看:65
本文介绍了Unmarshall与JAXB不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的XML,我想要解组成一个模型类。我用JAXB注释注释了类来定义访问类型(FIELD):

I have a simpe XML that I want to unmarshall into a model class. I have annotated the class with JAXB annotations for defining the access type (FIELD):

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DtoTest {

    private String name;

    public DtoTest() {}

    public DtoTest(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "DtoTest [name=" + name + "]";
    }
}

这是我运行unmarshal方法的主要类针对保存在String变量中的简单XML:

This is my main class where I run an unmarshal method against a simple XML saved in a String variable:

public class Test {

    public static void main(String[] args) throws Exception {
        Object obj = new DtoTest();
        String testXML = "<dtoTest><name>example</name></dtoTest>";
        obj = unmarshal(obj, testXML);
        System.out.println(obj);
    }

    /* This is a generic unmarshall method which I've already used with success with other XML*/
    public static <T> T unmarshal(T obj, String xml) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

        Class<? extends Object> type = obj.getClass();
        JAXBContext jc = JAXBContext.newInstance(type);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        obj =  (T)unmarshaller.unmarshal(xsr, type).getValue();
        xsr.close();

        return obj;
    }
}

每当我运行代码时,我得到相同的输出:

Whenever I run the code I get the same output:

DtoTest [name=null]

我不明白我做错了什么。

I don't understand what I'm doing wrong.

推荐答案

我刚刚在jdk1.7.0_67上运行你的代码并且它可以工作。

I've just run your code on jdk1.7.0_67 and it works.

DtoTest [name=example]

也许你对包含的库有些问题?我用普通的java运行它。

Maybe you have some problem with included libraries? I've run it with just plain java.

这篇关于Unmarshall与JAXB不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆