3

I need to send request using rest template. Before i send i need to marshall the object to xml when sending request. I got response from request but in XML format. Then i need to convert the response xml to Object in order to display the result onto interface.

Below is my controller where i send request

 @RequestMapping("/searchSummon")
 public String Search(Model model)
 {

    model.addAttribute("jaxbExample", new JAXBExample());
    model.addAttribute("pdxiRes", new PDXIRes());

    JAXBExample jaxbExample = new JAXBExample();
    String create_xml = jaxbExample.CreateXML();

    System.out.println(create_xml);

    RestTemplate restTemplate = new RestTemplate();
    String a = restTemplate.postForObject("http://192.168.80.30/summon-
    V2/example", "<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE PDXIReq 
    SYSTEM 'summon.dtd'>" + create_xml,String.class);

    System.out.println(a);

    return "searchSummon";
}

How i can unmarshall the 'a' to object? class for response PDXIRes Header Request Details Status

xml for response('a')

 <?xml version="1.0" encoding="utf-8"?>
 <PDXIRes>
 <header>
    <sp_code>abc017637m</sp_code>
 </header>
 <request id="1sq1216272728732">
    <id_no>683642435</id_no>
    <name>SALLY</name>
    <max_index>1024</max_index>
    <total_summons>2</total_summons>
    <summons_detail>
        <row num="1">
            <summons_id>1810000200002AQ639332</summons_id>
            <vehicle>NN162</vehicle>

        </row>
        <row num="2">
            <summons_id>1810000200002AM947772</summons_id>
            <vehicle>NN162</vehicle
        </row>
    </summons_detail>
    <status>
        <status_code>01</status_code>
        <status_msg>Successful</status_msg>
    </status>
   </request>
   </PDXIRes>
syafiqah
  • 391
  • 1
  • 6
  • 18
  • If you would use a REST framework like Jersey the marshalling/unmarshalling process is handled automatically... – Mathias G. Jul 31 '17 at 07:36
  • Please check if https://stackoverflow.com/questions/25704853/unmarshalling-nested-list-of-xml-items-using-jaxb helps... – deepakl Jul 31 '17 at 07:40

1 Answers1

3

You can do that using Unmarshaller.

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);

Found here: Use JAXB to create Object from XML String

CrazySabbath
  • 1,274
  • 3
  • 11
  • 33