七、List转JSON格式

List转JSON格式

将List的实例对象转为JSON格式:

  1. 导入fastjson包:

    com.alibaba
    fastjson
    1.2.58

  1. 测试代码如下:
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        List students = new ArrayList();
        students.add(new Student("xx", 20));
        students.add(new Student("xxx", 21));
        String str = JSON.toJSONString(students); // List转json
        System.out.println(str);
    }
}

class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}

你可能感兴趣的:(七、List转JSON格式)