Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี Deserialize JSON เป็น Java Object ด้วย Flexjson ใน Java

Flexjson เป็นไลบรารี Lightweight สำหรับ Serialize และ Deserialize Java Object เป็น/จาก JSON Format รองรับทั้ง Deep และ Shallow Copies ต้อง Import Package flexjson ใช้เมธอด deserialize() ของคลาส JSONDeserializer รับ JSON String Input ผลลัพธ์เป็น Static Typed Object Graph โดย Default ใช้ Property class ใน JSON Data เพื่อ Map Untyped Generic JSON Data เป็น Java Type เฉพาะ

Syntax

public T deserialize(String input)

ตัวอย่าง: Deserialize JSON เป็น Student Object

import flexjson.*;

public class DeserializeJSONTest {
    public static void main(String[] args) {
        JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>();
        String jsonStr = "{" + 
            "\"firstName\": \"Ravi\"," +
            "\"lastName\": \"Chandra\"," +
            "\"age\": 35," +
            "\"class\": \"Student\"," +
            "\"salary\": 50000.00" +
        "}";
        
        Student student = deserializer.deserialize(jsonStr);
        System.out.println(student);
    }
}

// Student class
class Student {
    private String firstName;
    private String lastName;
    private int age;
    private double salary;
    
    public Student() {}
    public Student(String firstName, String lastName, int age, double salary) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.salary = salary;
    }
    
    // getters, setters...
    public String toString() {
        return "Student[ firstName = " + firstName + ", lastName = " + lastName + 
               ", age = " + age + ", salary = " + salary + " ]";
    }
}

ผลลัพธ์

Student[ firstName = Ravi, lastName = Chandra, age = 35, salary = 50000.0 ]

จุดสำคัญ: JSON ต้องมี Field "class": "Student" เพื่อให้ Flexjson รู้ว่าจะ Deserialize เป็น Class ไหน (Type Information)