Fastjson generating and parsing JSON data
First, Fastjson generate JSON data
String jsonstrng = Json.tojsonstring (object);
Ii. Fastjson parsing JSON strings
1. JavaBean
User user = Json.parseobject (jsonstring,User. Class);
2. list<javabean>
list<User> Listperson =json.parsearray (jsonstring,User. Class);
3. list<string>
list<string> liststring = Json.parsearray (jsonstring, String.class);
4. list<map<string,object>>
list<map<string, object>> listmap = Json.parseobject (jsonstring, New typereference<list<map< String,object>>> () {});
Third, expand
1) When Fastjson generates JSON data, it exports empty data.
String jsonstr=json.tojsonstring (Userlist,serializerfeature.writemapnullvalue);
2) Fastjson parsing JSON data requires a value of NULL key can also parse out, it is necessary to use the Fastjson reflection.
list<map<string, object>> listmap = Json.parseobject (jsonstring, New typereference<list<map< String,object>>> () {});
The following is the test code, for reference only.
Import Java.util.arraylist;import java.util.hashmap;import Java.util.list;import Java.util.map;import Com.alibaba.fastjson.json;import Com.alibaba.fastjson.typereference;import Com.alibaba.fastjson.serializer.SerializerFeature; public class Test {public static void main (string[] args) {list<map<string,object>> userlist =getuserlist (); String jsonstr=json.tojsonstring (userlist,features); System.out.println (JSONSTR); list<map<string, object>> listmap = Json.parseobject (jsonstr, New typereference<list<map<string ,object>>> () {}); for (map<string, object> map:listmap) {System.out.println (json.tojsonstring (Map, Features));} }public static serializerfeature[] Features=new Serializerfeature[]{serializerfeature.writemapnullvalue, Serializerfeature.writenullbooleanasfalse,serializerfeature.writenulllistasempty, Serializerfeature.writenullstringasempty,serializerfeature.writedateusedateformat};p ublic static List<Map< String,object>> getuserlist () {LIst<map<string,object>> newlist=new arraylist<map<string,object>> (); for (int i=0;i<5;i+ +) {map<string,object> map=new hashmap<string,object> () map.put ("id", i); Map.put ("username", "xxx" +i); Map.put ("Sex", "male" +i), Map.put ("age", null), Map.put ("DH", null), Map.put ("zz", "ZZ" +i); Newlist.add (map);} return newlist;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Use of Fastjson