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


The JSON-lib is a Java library for serializing and de-serializing java beans, maps, arrays, and collections in JSON format. We can convert a bean to XML without type hints using the setTypeHintsEnabled() method of XMLSerializer class, this method sets whether JSON types can be included as attributes. We can pass false as an argument to this method to disable the type hints in XML.

Syntax

public void setTypeHintsEnabled(boolean typeHintsEnabled)

Example

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class ConvertBeanToXMLNoHintsTest {
   public static void main(String[] args) {
      Employee emp = new Employee("Krishna Vamsi", 115, 30, "Java");
      JSONObject jsonObj = JSONObject.fromObject(emp);
      System.out.println(jsonObj.toString(3)); //pretty print JSON
      XMLSerializer xmlSerializer = new XMLSerializer();
      xmlSerializer.setTypeHintsEnabled(false); // this method disable type hints
      String xml = xmlSerializer.write(jsonObj);
      System.out.println(xml);
   }
   public static class Employee {
      private String empName, empSkill;
      private int empId, age;
      public Employee(String empName, int empId, int age, String empSkill) {
         super();
         this.empName = empName;
         this.empId = empId;
         this.age = age;
         this.empSkill = empSkill;
      }
      public String getEmployeeName() {
         return empName;
      }
      public int getEmployeeId() {
         return empId;
      }
      public String getEmployeeSkill() {
         return empSkill;
      }
      public int getAge() {
         return age;
      }
   }
}

Output

{
   "employeeName": "Krishna Vamsi",
   "employeeSkill": "Java",
   "employeeId": 115,
   "age": 30
}
<?xml version="1.0" encoding="UTF-8"?>
<o>
   <age>30</age>
   <employeeId>115</employeeId>
   <employeeName>Krishna Vamsi</employeeName>
   <employeeSkill>Java</employeeSkill>
</o>


Updated on: 08-Jul-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements