首页 > 代码库 > Gson的应用测试

Gson的应用测试

关于将对象列表直接转为json数组

代码如下:

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

import com.google.gson.Gson;

public class JsonTest {
    public static void main(String[] args) {
        Person p1 =new Person("1", "zhangsan");
        Person p2 =new Person("2", "lisi");
        List<Person> list = new ArrayList<Person>();
        list.add(p1);
        list.add(p2);
        Gson gson = new Gson();
        String result = gson.toJson(list);
        System.out.println(result);//[{"id":"1","name":"zhangsan"},{"id":"2","name":"lisi"}]

    }
}


class Person{
    private String id;
    private String name;
    
    public Person(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

 

Gson的应用测试