Maison > Java > tutoriel Java > le corps du texte

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

王林
Libérer: 2023-09-22 15:25:02
avant
1479 Les gens l'ont consulté

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

JSON-lib 是一个 Java 库,用于序列化和反序列化 JSON 格式的 java beans、映射、数组和集合。我们可以使用 XMLSerializer 类的 setTypeHintsEnabled() 方法将 bean 转换为没有类型提示的 XML,该方法设置是否可以将 JSON 类型作为属性包含在内。我们可以将 false  作为参数传递给此方法,以禁用 XML 中的类型提示。

语法

public void setTypeHintsEnabled(boolean typeHintsEnabled)
Copier après la connexion

示例

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;
      }
   }
}
Copier après la connexion

输出

{
   "employeeName": "Krishna Vamsi",
   "employeeSkill": "Java",
   "employeeId": 115,
   "age": 30
}


   30
   115
   Krishna Vamsi
   Java

Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:tutorialspoint.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!