Home > Java > javaTutorial > body text

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

PHPz
Release: 2023-08-18 17:29:02
forward
579 people have browsed it

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)
Copy after login

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;
      }
   }
}
Copy after login

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"?-->
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!