package demo;
public class Person {
private String name;
private int age;
public Person(){
}
public Person(String name,int age){
this.setAge(age);
this.setName(name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "name:"+this.getName()+"---------age:"+this.getAge();
}
}
package demo;
import ;
import ;
import ;
import ;
import .*;//要导入的fastjson包
public class ListToJsonDemo {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
List<Person> list1=new ArrayList<Person>();
(new Person("xinghang",2));
(new Person("zilong",4));
String str1=(new Person("xinghang",666));// 对象转JSON字符串
Person p1=(str1, );//JSON字符串转对象
String str=(list1);//list转json字符串
List<Person> person = (str, ); //json字符串转list
(str1);
(p1);
for(Person p:person){
(p);
}
}
}
打印结果:
{"age":666,"name":"xinghang"}
name:xinghang---------age:666
name:xinghang---------age:2
name:zilong---------age:4