How to convert a bean to XML using JSON-lib API in Java?


The net.sf.json.xml.XMLSerializer class is a utility class for transforming JSON to XML. When transforming JSONObject instance to XML, this class can add hints for converting back to JSON. We can use the write() method of XMLSerializer class to write a JSON value into an XML string with UTF-8 encoding and it can return a string representation of a well-formed XML document.

Syntax

public String write(JSON json)

Example

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class ConvertBeanToXMLTest {
   public static void main(String[] args) {
      Student student = new Student("Sai", "Adithya", 25, "Pune");
      JSONObject jsonObj = JSONObject.fromObject(student);
      System.out.println(jsonObj.toString(3)); //pretty print JSON
      XMLSerializer xmlSerializer = new XMLSerializer();
      String xml = xmlSerializer.write(jsonObj);
      System.out.println(xml);
   }
   public static class Student {
      private String firstName, lastName, address;
      public int age;
      public Student(String firstName, String lastName, int age, String address) {
         super();
         this.firstName = firstName;
         this.lastName = lastName;
         this.age = age;
         this.address = address;
      }
      public String getFirstName() {
         return firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public int getAge() {
         return age;
      }
      public String getAddress() {
         return address;
      }
   }
}

Output

{
   "firstName": "Sai",
   "lastName": "Adithya",
   "address": "Pune",
   "age": 25
}
<?xml version="1.0" encoding="UTF-8"?>
<o>
   <address type="string">Pune</address>
   <age type="number">25</age>
   <firstName type="string">Sai</firstName>
   <lastName type="string">Adithya</lastName>
</o>

raja
Published on 06-Nov-2019 06:58:39
Advertisements