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

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

王林
王林forward
2023-09-22 15:25:021582browse

如何在Java中使用JSON-lib API将bean转换为没有类型提示的XML?

JSON-lib is a Java library for serializing and deserializing java beans, maps, arrays and collections in JSON format. We can convert a bean to XML without type hints using the setTypeHintsEnabled() method of the XMLSerializer class, which sets whether JSON types can be included as attributes. We can pass false as parameter to this method to disable 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>
<!--?xml version="1.0" encoding="UTF-8"?-->

The above is the detailed content of How to convert bean to XML without type hints 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