Fastjson Simple to use

Source: Internet
Author: User
Tags object object serialization

Fastjson is a high-performance, fully functional, standard JSON library written in the Java language that supports http://json.org . More do not say, Baidu a lot.

Here, simply summarize the methods you have used and tested.

If you use MAVEN, add the following dependencies to the Pom.xml file.

<dependency>     <groupId>com.alibaba</groupId>     <artifactid>fastjson</ artifactid>     <version>1.2.15</version> </dependency>

  

Serialization of

Serialization refers to a string that turns the JavaBean object into a JSON format.

Com.alibaba.fastjson.JSON provides a number of methods (polymorphic) for serialization.

1. Basic serialization
String Objjson = Json.tojsonstring (Object object);

  

Pass in an object and turn the object into a JSON string.

Example 1: Turning a map into JSON

map<string, object> map = new hashmap<string, object> (); Map.put ("Key1", "one"); Map.put ("Key2", "both");          String Mapjson = json.tojsonstring (map);

  

Output Result:

{"Key1": "One", "Key2": "One"}

  

Example 2: Turn list<map> into JSON.

list<map<string, object>> list = new arraylist<map<string, object>> ();          map<string, object> map1 = new hashmap<string, object> (); Map1.put ("Key1", "one"); Map1.put ("Key2", "both");          map<string, object> map2 = new hashmap<string, object> (); Map2.put ("Key1", "three"); Map2.put ("Key2", "four");         List.add (MAP1); List.add (MAP2);      String Listjson = json.tojsonstring (list);

  

Output Result:

[{"Key1": "One", "Key2": "Both"},{"Key3": "Three", "Key4": "Four"}]

  

Example 3: Custom JavaBean user turns JSON.

User user = new user (); User.setusername ("John Doe"); User.setage ();          String Userjson = json.tojsonstring (user);

  

Output Result:

{"Age": $, "userName": "John Doe"}

  

You can output a formatted JSON string.

String Objjson = Json.tojsonstring (Object object, Boolean Prettyformat);

  

Passes in an object and a Boolean type (whether formatted), and turns the object into a formatted JSON string.

Example 4: Take example 2 code for example.

String Listjson = json.tojsonstring (list, true);

  

The output is:

[      {          "Key1": "One",          "Key2": "One"      },      {        "Key3": "Three",          "Key4": "Four"    }]

  

Fastjson provides a number of feature support.

  

A mutable variable that passes in an object and Serializerfeature type. Serializerfeature is an enumeration.

Com.alibaba.fastjson.serializer.SerializerFeature

You can use these features according to your own situation.

Briefly say a few common features:

1. Date formatting:

Fastjson can be formatted directly on a date type and, by default, Fastjson will convert date to long.

Example 5:fastjson turns java.util.Date into a long.

String Datejson = json.tojsonstring (New Date ());         System.out.println (Datejson);

  

Output Result:

1401370199040

  

Example 6: Formatting dates with the Serializerfeature attribute.

String Datejson = json.tojsonstring (New Date (), serializerfeature.writedateusedateformat);         System.out.println (Datejson);

  

Output Result:

"2014-05-29 21:36:24"

  

You can also specify the output date format.

Example 7: Specify the output date format.

String Datejson = Json.tojsonstringwithdateformat (New Date (), "Yyyy-mm-dd HH:mm:ss. SSS ");          System.out.println (Datejson);

  

Output Result:

"2014-05-29 21:47:00.154"

  

2. Use single quotation marks.

Example 8: Take example 2 for example.

String Listjson = json.tojsonstring (list, serializerfeature.usesinglequotes);

  

Output Result:

[{' Key1 ': ' One ', ' key2 ': ' Both '},{' Key3 ': ' Three ', ' Key4 ': ' Four '}]

  

3.JSON format.

Example 9:

String Listjson = json.tojsonstring (list, serializerfeature.prettyformat);

  

Output: Consistent with example 4 results.

4. Output a null field.

By default Fastjson does not enter a field with a value of NULL, you can use Serializerfeature.writemapnullvalue to make it output.

Example 10:

map<string, object> map = new hashmap<string,object> ();          String B = null; Integer i = 1;          Map.put ("A", b); Map.put ("B", I);          String Listjson = json.tojsonstring (map, Serializerfeature.writemapnullvalue);

  

Output Result:

{"A": null, "B": 1}

  

5. Serialization is the write type information.

Example 11:

User user = new user ();          User.setage (18); User.setusername ("John Doe");          String Listjson = json.tojsonstring (user, serializerfeature.writeclassname);

  

Output Result:

{"@type": "User", "Age": "UserName": "John Doe"}

  



Because serialization has type information, it enables type recognition to be automated when deserializing.

Example 12: Deserialization of Example 11.

User User1 = (user) json.parse (listjson);          System.out.println (User1.getage ());

  

Output Result:

18

  

If user serialization is not joined to type information (serializerfeature.writeclassname), an error (Java.lang.ClassCastException) will be followed by example 12.

deserialization

Deserialization is the conversion of a JSON-formatted string into a Java bean object.

Com.alibaba.fastjson.JSON provides a number of methods (polymorphic) for deserialization

Give a few examples.

Specifies the class information to deserialize.

Example 13: Deserialization of Example 3.

User user1 = Json.parseobject (Userjson, User.class); System.out.println (User1.getusername ());

  

Output Result:

John doe

  

Sets the deserialization of the collection.

Example 14: Deserialization of Example 2.

List<map> List1 = Json.parsearray (Listjson, map.class);           For (map<string, object> map:list1) {     System.out.println (map.get ("Key1"));     System.out.println (Map.get ("Key2"));          }

  

Output Result:

One, three four

  

The deserialization of generics (using TypeReference to pass in type information).

Example 15: Deserialization of Example 1.

map<string, object> map1 = Json.parseobject (Mapjson, New typereference<map<string, Object>> () {}); System.out.println (Map1.get ("Key1")); System.out.println (Map1.get ("Key2"));

  

Output Result:

Onetwo

  

--------------------------------------------------------------------------------------------------------------- ------------------------------------------

Jsonobject,jsonarray is the two subclass of JSON.

Jsonobject equivalent to map<string, Object>

Jsonarray equivalent to list<object>.

An example of a simple method:

Example 16: Convert Map to Jsonobject, then add element, output.

map<string, object> map = new hashmap<string, object> ();  Map.put ("Key1", "one");  Map.put ("Key2", "both");                               Jsonobject j = new Jsonobject (map);                       J.put ("Key3", "three");              System.out.println (J.get ("Key1")); System.out.println (J.get ("Key2")); System.out.println (J.get ("Key3"));

  

Output Result:

One and three

  

Example 17: Turn the list object into Jsonarray and output.

list<map<string, object>> list = new arraylist<map<string, object>> ();            map<string, object> map = new hashmap<string, object> ();  Map.put ("Key1", "one"); Map.put ("Key2", "both");            map<string, object> map2 = new hashmap<string, object> ();  Map2.put ("Key1", "three");  Map2.put ("Key2", "four");          List.add (map); List.add (MAP2);          Jsonarray j = Jsonarray.parsearray (json.tojsonstring (list));           for (int i=0; i<j.size (); i++) {     System.out.println (J.get (i));

  

Output Result:

{"Key1": "One", "Key2": "One"} {"Key1": "Three", "Key2": "Four"}

  

Fastjson Simple to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.