如何在java spring-boot上将xml转换为对象

Mr *_*r K 6 java xml object spring-boot

您好,我正在尝试使用对象数量转换 xml,但收到一条错误消息:根元素后面的文档中的标记必须格式正确。

XML:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="test.example.com">
  <Item>
    <ItemKey>1111</ItemKey>
    <Start>2/10/2017</Start>
    <customNumber>12</customNumber>
    <End>2/10/2018</End>
    <Account>2221111</Account>
    <Name>John</Name>
    <Note>GOOD</Note>
    <CodeNo>4444-1</CodeNo>
    <Source>www.cnn.com</Source>
  </Item>
  <Item>
    <ItemKey>2222</ItemKey>
    <Start>2/10/2017</Start>
    <customNumber>75</customNumber>
    <End>2/10/2018</End>
    <Account>3333111</Account>
    <Name>Smith</Name>
    <Note>NOT GOOD</Note>
    <CodeNo>4444-2</CodeNo>
    <Source>www.fox.com</Source>
  </Item>
</string>
Run Code Online (Sandbox Code Playgroud)

型号类别:

package example.models;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Item")
public class Model {

private String CodeNo;

private String ItemKey;

private String Start;

private String End;

private String Account;

private String Name;

private String Note;

...(gets and sets)
Run Code Online (Sandbox Code Playgroud)

主要代码:

StringReader reader = new StringReader(response);
String response = restTemplate.getForObject(url, String.class);
...

 JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Model recordes = (Model) unmarshaller.unmarshal(reader);
Run Code Online (Sandbox Code Playgroud)

unmarshal 异常:文档中根元素后面的标记必须格式正确。

xml 中只有一项代码可以工作。

我缺少什么并且需要做什么才能没有错误地获取元素(项目)对象列表?

小智 -1

int PRETTY_PRINT_INDENT_FACTOR = 4;
String TEST_XML_STRING =
        "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to 
JSON</test>";

try {
     JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
     String jsonPrettyPrintString = 
xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
     System.out.println(jsonPrettyPrintString);
} catch (JSONException je) {
     System.out.println(je.toString());
}
Run Code Online (Sandbox Code Playgroud)

希望这对您有帮助,使用org.json jar 文件