Serialization is the process of converting the object state information to a form that can be stored or transmitted. During serialization, the object writes its current state to the temporary or persistent storage area. Later, you can re-create the object by reading or deserializing the object status from the bucket. Serialization is the process of converting the object state to a format that can be maintained or transmitted. In contrast to serialization, deserialization converts a stream into an object. These two processes can be combined to easily store and transmit data.
The following example describes how to use fastjson to complete serialization and deserialization:
Person:
Public class Person {private String name; private int age;/** for the second example below, this empty constructor is required; otherwise: com. alibaba. fastjson. JSONException: * default constructor not found. class com. test. person */public Person () {} public Person (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}
The following are the actual serialization and deserialization results:
Import com. alibaba. fastjson. JSON; public class Serialization {public static void main (String [] args) {Person person = new Person ("XiaoMing", 16); // serialize String text = JSON. toJSONString (person); System. out. println (text); // deserialize Person person1 = JSON. parseObject (text, Person. class); System. out. println (person1.getName () + "," + person1.getAge ());}}
Result:
{"Age": 16, "name": "XiaoMing "}
XiaoMing, 16
For List serialization and deserialization:
public class People {private String id;private List
list = new ArrayList
();public String getId() {return id;}public void setId(String id) {this.id = id;}public List
getList() {return list;}public void setList(List
list) {this.list = list;}}
Import com. alibaba. fastjson. JSON; public class SerializationList {public static void main (String [] args) {People people = new People (); people. setId ("10012"); Person p1 = new Person ("XiaoMing", 16); Person p2 = new Person ("XiaoFang", 15); List
List = new ArrayList
(); List. add (p1); list. add (p2); people. setList (list); // serialize String text = JSON. toJSONString (people); System. out. println (text); // deserialize People p = JSON. parseObject (text, People. class); System. out. println (p. getId (); for (Person person: p. getList () {System. out. println (person. getName () + "," + person. getAge ());}}}
Result:
{"Id": "10012", "list": [{"age": 16, "name": "XiaoMing" },{ "age": 15, "name": "XiaoFang"}]}
10012
XiaoMing, 16
XiaoFang, 15