Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chuyển Bean thành XML dùng JSON-lib API (Java)

net.sf.json.xml.XMLSerializer chuyển JSONObject → XML string (UTF-8). Mặc định bật type hints (attribute type).

Cú pháp

public String write(JSON json)

Ví dụ minh họa

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class BeanToXmlTest {
    public static void main(String[] args) {
        Student student = new Student("Sai", "Adithya", 25, "Pune");
        JSONObject jsonObj = JSONObject.fromObject(student);
        System.out.println("JSON: " + jsonObj.toString(3));
        
        XMLSerializer xmlSerializer = new XMLSerializer();
        String xml = xmlSerializer.write(jsonObj); // Mặc định có type hints
        System.out.println("XML:\n" + xml);
    }
    
    static class Student {
        private String firstName, lastName, address;
        public int age;
        // constructor, getters...
    }
}

Output

JSON:
{
  "firstName": "Sai",
  "lastName": "Adithya",
  "address": "Pune",
  "age": 25
}

XML:


  
Pune
25 Sai Adithya

Đặc điểm XMLSerializer

  • Root element luôn là <o> (object) - ít tùy biến.
  • Type hints giúp round-trip XML→JSON chính xác type.
  • Attribute sorting: alphabetical.
  • Hỗ trợ nested object, array.

Alternative hiện đại: Jackson XML


// Dependency: com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.15+
XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(student);
// Output: Sai... (root = class name)

So sánh

Đặc điểm JSON-lib XMLSerializer Jackson XmlMapper
Root element Fixed <o> Tùy biến (class name hoặc annotation)
Type hints Có (bật/tắt) Không mặc định, có option
Annotation support Không Đầy đủ (@JacksonXmlProperty, @JacksonXmlRootElement...)
Maintenance Stopped (2010) Active, widely used

Khuyến nghị

Không dùng JSON-lib cho dự án mới. Jackson XML là standard hiện nay, tích hợp tốt với Jackson JSON, annotation nhất quán, hiệu suất cao.