1、理解:是阿里巴巴公司开源json的工具包
2、先上两个链接:https://www.cnblogs.com/wgale025/p/5875430.html
http://www.oschina.net/code/snippet_228315_35122
3、代码示例:
//先创建一个对象
public class TestPerson {
private int age;
private String name;
public TestPerson() {
// 之所以要空的构造方法是因为json反序列化是需要
}
public TestPerson(int age,String name) {
this.age=age;
this.name=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;
}
}
//再编写json的序列化和反序列化示例
public class TestFastJson {
public static void main(String[] args) {
TestPerson person=new TestPerson(19,"tudou");
List<TestPerson> list=new ArrayList<>();
list.add(person);
list.add(new TestPerson(18, "xigua"));
//对象序列化为json对象
Object json1 = JSON.toJSON(person);
System.out.println(json1);
System.out.println("----------------------------------------------------------");
//对象集合序列化为json对象
Object json2=JSON.toJSON(list);
System.out.println(json2);
System.out.println("----------------------------------------------------------");
//json对象反序列化为对象(对象确定的情况下)
TestPerson testPerson=JSON.parseObject(json1.toString().replace("\"", "\""), TestPerson.class);
System.out.println(testPerson.getName()+"----"+testPerson.getAge());
System.out.println("----------------------------------------------------------");
//json独享反序列化为对象集合(对象确定的情况下)
List<TestPerson> testPersonList=JSON.parseArray(json2.toString().replace("\"", "\""), TestPerson.class);
for (TestPerson testPerson2 : testPersonList) {
System.out.println(testPerson2.getName()+"---"+testPerson2.getAge());
}
System.out.println("----------------------------------------------------------");
//json对象反序列化为对象(对象不确定的情况下)
JSONObject jsonObject=JSON.parseObject(json1.toString().replace("\"", "\""));
System.out.println(jsonObject.getString("name")+"---"+jsonObject.getIntValue("age"));
System.out.println("----------------------------------------------------------");
//json独享反序列化为对象集合(对象不确定的情况下)
JSONArray jarr = JSON.parseArray(json2.toString().replace("\"", "\""));//[{},{},{}]
for (int i = 0; i < jarr.size(); i++) {
JSONObject temp=jarr.getJSONObject(i);//{}
System.out.println(temp.getString("name")+"---"+temp.getIntValue("age"));
}
System.out.println("----------------------------------------------------------");
//下面这个你看着玩就可以了,没什么用
JSONArray jsonObjectList=JSON.parseArray(json2.toString().replace("\"", "\""));
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("[");
for (Object jsonObjectList2 : jsonObjectList) {
stringBuffer.append(jsonObjectList2.toString()).append(",");
}
stringBuffer.deleteCharAt(stringBuffer.length()-1);//这里不能直接用stringBuffer.subString("","")
stringBuffer.append("]");
System.out.println(stringBuffer.toString());
}
}