Home > Java > javaTutorial > body text

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

王林
Release: 2023-09-22 15:25:02
forward
1533 people have browsed it

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

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

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

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!

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!