How to convert a fastjson string to an object?

Using the fastjson library makes it easy to convert a JSON string into a Java object. Here is a simple example:

import com.alibaba.fastjson.JSON;

public class Main {
    public static void main(String[] args) {
        // JSON字符串
        String jsonString = "{\"name\":\"Alice\",\"age\":25,\"city\":\"Beijing\"}";

        // 将JSON字符串转换为Java对象
        Person person = JSON.parseObject(jsonString, Person.class);

        // 输出Java对象
        System.out.println(person.getName()); // Alice
        System.out.println(person.getAge()); // 25
        System.out.println(person.getCity()); // Beijing
    }
}

// 定义Person类
class Person {
    private String name;
    private int age;
    private String city;

    // 必须提供默认构造方法
    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

In the code above, we first define a Person class that includes three properties: name, age, and city. Then, we use the JSON.parseObject() method from fastjson to convert a JSON string into a Person object. Finally, we can access the property values by using the getter methods of the Person object.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds