
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert 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>
Advertisements