JSONArray数据转换成java List

package no.integrasco.ingentia.news.qaedition;

public class Person {

    private String name;

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



package no.integrasco.ingentia.news.qaedition;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class JsonTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // 转换方法1
        JSONArray array = JSONArray.fromObject("[{'name':'hehe','age':22}]");
        List<Person> list = JSONArray.toList(array, Person.class);// 过时方法
        System.out.println(list.get(0).getName());

        // 转换方法2
        List<?> list2 = JSONArray.toList(array, new Person(), new JsonConfig());//参数1为要转换的JSONArray数据,参数2为要转换的目标数据,即List盛装的数据
        Person person = (Person) list2.get(0);
        System.out.println(person.getAge());
    }

}

你可能感兴趣的:(json)