Java之fastjson学习

xiaoxiao2021-02-27  301

我刚学会写稍微复杂一点点的接口,还在沾沾自喜中,被大哥鄙视了一顿,说太简单,让我立马学fastjson,据说是最快最好用的。然后我就赶紧学了

fastjson jar包下载

上代码:

person实体类:

public class Person { private int age; private String name; public Person(){ } public Person(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; } }

main: import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class TestFastJson { public static void main(String[] args) { // TODO Auto-generated method stub Person json = new Person(23,"Billy Lu"); List<Person> list = new ArrayList<Person>(); list.add(json); list.add(new Person(22,"Bruce Lu")); //将集合或者对象序例化成JSON System.out.println("line 18: "+JSON.toJSON(json)); System.out.println("line 19: "+ JSON.toJSON(list) ); //Json串反序列化成对象 Person person = JSON.parseObject("{\"name\":\"Billy Lu\",\"age\":23}", Person.class); System.out.printf("line 22: "+"name:%s,age:%d\n",person.getName(),person.getAge()); String str = "[{\"name\":\"Billy Lu\",\"age\":23},{\"name\":\"Bruce Lu\",\"age\":22}]"; //数组对象反序列化成集合 List<Person> listPerson = JSON.parseArray(str,Person.class); for(Person item : listPerson){ System.out.println("line 29: "+ item.getName() ); System.out.println("line 30: "+ item.getAge()); } //没有对象直接解析JSON对象 JSONObject jobj = JSON.parseObject("{\"name\":\"Billy Lu\",\"age\":23}"); System.out.printf("line 35: "+"name:%s,age:%d\n",jobj.getString("name"),jobj.getBigInteger("age")); //没有对象直接解析JSON数组 JSONArray jarr = JSON.parseArray("[{\"name\":\"Billy Lu\",\"age\":23},{\"name\":\"Bruce Lu\",\"age\":22}]"); for(int i=0,len=jarr.size();i<len;i++){ JSONObject temp= jarr.getJSONObject(i); System.out.printf("line 42: "+"name:%s,age:%d\n",temp.getString("name"),temp.getBigInteger("age")); } for(Object obj:jarr){ System.out.println("line 46: "+obj.toString()); } } }

结果:

line 18: {"age":23,"name":"Billy Lu"} line 19: [{"age":23,"name":"Billy Lu"},{"age":22,"name":"Bruce Lu"}] line 22: name:Billy Lu,age:23 line 29: Billy Lu line 30: 23 line 29: Bruce Lu line 30: 22 line 35: name:Billy Lu,age:23 line 42: name:Billy Lu,age:23 line 42: name:Bruce Lu,age:22 line 46: {"age":23,"name":"Billy Lu"} line 46: {"age":22,"name":"Bruce Lu"}

结论:确实好用!

转载请注明原文地址: https://www.6miu.com/read-3388.html

最新回复(0)