gpt4 book ai didi

java - 使用 Jaxb unmarshal/marshal 时线程 "main"java.lang.NullPointerException 中出现异常

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:36 27 4
gpt4 key购买 nike

我正在使用 JAXB 将给定的输入 Xml 文件解码为 Java 对象然后将其编码(marshal)回 Xml 字符串。我的 Xml 文件如下所示:

<bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" id="_Definitions_1">
<bpmn2:process id="_500441" name="process">
</bpmn2:process>
</bpmn2:definitions>

定义.类:

@XmlRootElement(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL")
public class Definitions {
@XmlAttribute
private String id;

@XmlElement(name = "bpmn2:process")
private Process process;

@XmlElement(name = "bpmndi:BPMNDiagram")
private Diagram diagram;

public Definitions() {
}
public Definitions(String id, Process process, Diagram diagram) {
this.id = id;
this.process = process;
this.diagram = diagram;
}
public Process getProcess() {
return process;
}
public Diagram getDiagram() {
return diagram;
}
public String getId() {
return id;
}
}

流程.类:

@XmlAccessorType(XmlAccessType.FIELD)
public class Process {
@XmlAttribute
private String id;
public Process() {
}
public Process(String id) {
this.id = id;
}
public String getId() {
return id;
}
}

模型.类:

public class Model {
@XmlElement
private Process process;
public Model() {
}
public Model(String processId, Process p) {
this.id = processId;
this.process = p;
}
}

主要方法:

public static void main(String[] args) throws IOException, JSONException, JAXBException {
BpmnToJsonImport bj = new BpmnToJsonImport();
InputStream is = BpmnToJsonImport.class.getResourceAsStream("myXml.txt");
String Str = IOUtils.toString(is);
StringReader sr = new StringReader(Str);
JAXBContext context = JAXBContext.newInstance(Definitions.class, Model.class);
Unmarshaller unmarshaller = context.createUnmarshaller();

Definitions d = (Definitions) unmarshaller.unmarshal(sr);
Model model = new Model(d.getProcess().getId(), d.getProcess());

StringWriter sw = new StringWriter();

Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(model, sw);
String str = sw.toString();
System.out.println(str);

}

当它尝试使用 d.getProcess.getId 检索进程 id 时,我得到了 java.lang.NullPointerException

最佳答案

您错误地映射了命名空间限定。元素名称中不得包含前缀。

@XmlElement(name = "BPMNDiagram")
private Diagram diagram;

要映射命名空间限定,您可以使用包级别 @XmlSchema 注释。

package-info.java

@XmlSchema( 
namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

了解更多信息

关于java - 使用 Jaxb unmarshal/marshal 时线程 "main"java.lang.NullPointerException 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782578/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com