0

Im trying to read a json and send it back to a server in the form of XML. Im able to read the json successfully but i need to send a xml from what i have read which is in my endpoint

  URL url = new URL("https://xxxx.xxx/xxxx/post");
  HttpURLConnection http = (HttpURLConnection)url.openConnection();
  http.setRequestMethod("POST");
  http.setDoOutput(true);
  http.setRequestProperty("Content-Type", "application/xml");
  http.setRequestProperty("Accept", "application/xml");

  String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Request>\n    <Login>login</Login>\n    
  <Password>password</Password>\n</Request>";

  byte[] out = data.getBytes(StandardCharsets.UTF_8);

  OutputStream stream = http.getOutputStream();
  stream.write(out);

  System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
  http.disconnect();

Currently im hardcoding string data, but i want to send the data which is in my rest endpoint http://localhost:8080/login if i hit this endpoint im getting a XML

<ArrayList>
  <item>
    <Login>1000<Login>
    <Password>Pwd<Password>
  </item>
</ArrayList>

How can i read this endpoint and use as String data

1 Answers1

1

i dont often answer but I think I have encountered a situation like this. If I understand This correctly, you want to convert a JSON string to a XML

I suppose you could use a Marshaller to convert the JOSN to a POJO object (or alternatively convert to a JSONObject) and then Marshaller it out to XML. For a simple solution I would recommend using Jackson (plus if you are using something like Spring Boot Jackson comes bundled in)
Maven

<dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.11.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
           <version>2.7.4</version>
    </dependency>

say we have a JSON like:

[{"id":1,"name":"cat food"},{"id":2,"name":"dog food"}]

we can create a Java class like:

class MappingObject{
    public Integer id;
    public String name;
//Getters and setters 
...
}

And now we can use a Marshaller to convert it to a POJO and then to a XML.

ObjectMapper objectMapper = new ObjectMapper();
List<MappingObject> parsedDataList= objectMapper.readValue(result, new TypeReference<List<MappingObject>>(){});
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(reparsedDataList);
System.out.println("This is the XML version of the Output : "+xml);

I think this question is close to your question: simple-method-to-convert-json-to-xml

KidCoader
  • 26
  • 2