需要的fast-json jar包,下载地址:fast-json jar包地址
package heheda;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUse {
private String name;
private String address;
private Integer age;
public JsonUse() {
super();
}
public JsonUse(String name, String address, Integer age) {
super();
this.name = name;
this.address = address;
this.age = age;
}
@Override
public String toString() {
return "[name=" + name + ", address=" + address + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static void main(String[] args) {
JsonUse jsonUse = new JsonUse();
jsonUse.setAddress("上海");
jsonUse.setAge(18);
jsonUse.setName("李雷");
JsonUse jsonUse2 = new JsonUse();
jsonUse2.setAddress("北京");
jsonUse2.setAge(20);
jsonUse2.setName("韩梅梅");
List<JsonUse> list = new ArrayList<JsonUse>();
// JsonUse对象转JSON串
String jsonString = JSON.toJSONString(jsonUse);
System.out.println("jsonString:" + jsonString);
// JSON串转用jsonUse对象
JsonUse jsonUse3 = JSON.parseObject(jsonString, JsonUse.class);
String nameString = jsonUse3.name;
System.out.println("nameString:" + nameString);
System.out.println("jsonUse3:" + jsonUse3);
// 构建JsonUse对象数组
JsonUse[] users = new JsonUse[2];
users[0] = jsonUse;
users[1] = jsonUse2;
// 用户对象数组转JSON串
String jsonString2 = JSON.toJSONString(users);
System.out.println("jsonString2:" + jsonString2);
// JSON串转用户对象列表
List<JsonUse> users2 = JSON.parseArray(jsonString2, JsonUse.class);
System.out.println("users2:" + users2);
}
}
结果: