JaxB 解组器错误

JaxB Unmarshaller Error

我正在尝试使用 JaxB 解组一个基本的 XML 文件,但是代码有问题。编组器正确运行但是解组器,而不是返回 XML 文件中的内容,returns com.project.test.Jaxb@094jufd34c。 (class 的名称后跟字母和数字的随机组合的“@”)。这是下面的代码。感谢您的帮助或想法。

XML 注释类:

@XmlRootElement
public class Jaxb {
String newString;

public String getNewString() {
    return newString;
}

@XmlElement
public void setNewString(String newString) {
    this.newString = newString;
}
}

编组器:

public class Marshal {
Jaxb newWindow = new Jaxb();
String xmlString;

void marshal(String[] args) {

    xmlString="a,b,c";

    newWindow.setNewString(xmlString);

 try {

        File file = new File("newXml.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Jaxb.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(newWindow, file);
        jaxbMarshaller.marshal(newWindow, System.out);

          } catch (JAXBException e) {
        e.printStackTrace();
          }
}
}

解组器:

public class unmarshal {

static String unMarshal() {
  String unmarshString="";
  try {

        File x = new File("newXml.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Jaxb.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Jaxb newUnmarshal = (Jaxb) jaxbUnmarshaller.unmarshal(x);

        unmarshString = newUnmarshal.toString();

      } catch (JAXBException e) {
        e.printStackTrace();
        System.out.print("error");
      }
  return unmarshString;
}
}

com.project.test.Jaxb@094jufd34cJaxb class 上默认 toString() 实现的输出。覆盖 toString 以输出任何你需要的输出,例如

public String toString() {
    return newString;
}

不过,我猜既然你的 unmarshal 方法专门 returns 一个字符串,那么你真正想要做的只是 unmarshString = newUnmarshal.getNewString() 而不是 unmarshString = unmarshal.toString()

The name of the class followed by an '@' with a random combination of letters and numbers

它不是随机的,它是由 javadoc for Object#toString

定义的

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

这与 XML 或 JAXB 无关,这只是如何在 class.

上定义 toString