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

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

PHPz
PHPzforward
2023-08-18 17:29:02557browse

net.sf.json.xml.XMLSerializer class is a utility class used to convert JSON to XML. When converting a JSONObject instance to XML, the class can add hints for conversion back to JSON. We can use the write() method of the XMLSerializer class to write a JSON value into an XML string with UTF-8 encoding, and it can return a well-formed string representation of the 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>
<!--?xml version="1.0" encoding="UTF-8"?-->

The above is the detailed content of How to convert a bean to XML using JSON-lib API in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete