Fastjson conversion between JSON-formatted strings, JSON objects, and JavaBean

Source: Internet
Author: User

Fastjson the parsing of JSON format strings mainly uses three classes:

Json:fastjson parser for converting JSON-formatted strings to JSON objects and JavaBean.

The JSON object provided by the Jsonobject:fastjson.

Jsonarray:fastjson provides a JSON array object.

We can think of Jsonobject as a map<string,object>, but Jsonobject provides a richer and more convenient way to manipulate object properties. Let's look at the source code.

Similarly, we can think of Jsonarray as a list<object>, and we can think of Jsonarray as a collection of Jsonobject objects.

In addition, because Jsonobject and Jsonarray inherit JSON, they can also be used to convert JSON format strings to JSON objects and javabean directly, but to avoid confusion we still use JSON.

First, define three JSON-formatted strings as our data source.

//JSON string-Simple Object typePrivate Static FinalString json_obj_str = "{\" studentname\ ": \" lily\ ", \" studentage\ ": 12}";//JSON string-array typePrivate Static FinalString json_array_str = "[{\" studentname\ ": \" lily\ ", \" studentage\ ": 12},{\" studentname\ ": \" lucy\ ", \" Studentage\ " : 15}] ";//complex format JSON stringPrivate Static FinalString complex_json_str = "{\" teachername\ ": \" crystall\ ", \" teacherage\ ": 27,\" course\ ": {\" coursename\ ": \" English\ " , \ "code\": 1270},\ "students\": [{\ "studentname\": \ "lily\", \ "studentage\": 12},{\ "studentname\": \ "lucy\", \ " Studentage\ ": 15}]}";

Example 1:json a conversion between a format string and a JSON object.

Example 1.1-json string-conversion between a simple object type and a Jsonobject

    /**     * JSON string-conversion     between Simple object type and Jsonobject */public    Static  void  testjsonstrtojsonobject () {        = json.parseobject (json_obj_str);         //  // because Jsonobject inherits JSON, so this is also possible         System.out.println ( Jsonobject.getstring ("studentname") + ":" +jsonobject.getinteger ("Studentage");    }

Example 1.2-json string-conversion between array type and Jsonarray

    /*** JSON string-conversion between array type and Jsonarray*/     Public Static voidTestjsonstrtojsonarray () {Jsonarray Jsonarray=Json.parsearray (JSON_ARRAY_STR); //Jsonarray jsonArray1 = Jsonarray.parsearray (JSON_ARRAY_STR);//because Jsonarray inherits the JSON, so it's also possible.//Traversal mode 1        intSize =jsonarray.size ();  for(inti = 0; i < size; i++) {Jsonobject jsonobject=Jsonarray.getjsonobject (i); System.out.println (Jsonobject.getstring ("Studentname") + ":" +jsonobject.getinteger ("Studentage"))); }        //Traversal mode 2         for(Object obj:jsonarray) {jsonobject jsonobject=(jsonobject) obj; System.out.println (Jsonobject.getstring ("Studentname") + ":" +jsonobject.getinteger ("Studentage"))); }    }

Example 1.3-conversion between a complex JSON format string and Jsonobject

    /*** Conversion between complex JSON format strings and Jsonobject*/     Public Static voidTestcomplexjsonstrtojsonobject () {jsonobject jsonobject=Json.parseobject (COMPLEX_JSON_STR); //Jsonobject JsonObject1 = Jsonobject.parseobject (COMPLEX_JSON_STR);//because Jsonobject inherits the JSON, so it's also possible.String TeacherName= Jsonobject.getstring ("TeacherName"); Integer Teacherage= Jsonobject.getinteger ("Teacherage"); Jsonobject Course= Jsonobject.getjsonobject ("Course"); Jsonarray Students= Jsonobject.getjsonarray ("Students"); }

Example 2:json the conversion between a format string and JavaBean.

First, we provide three JavaBean for the string shown in the data source.

 Public classStudent {PrivateString Studentname; PrivateInteger Studentage;  PublicString Getstudentname () {returnStudentname; }     Public voidsetstudentname (String studentname) { This. Studentname =Studentname; }     PublicInteger getstudentage () {returnStudentage; }     Public voidsetstudentage (Integer studentage) { This. Studentage =Studentage; }}
 Public classCourse {PrivateString Coursename; PrivateInteger Code;  PublicString Getcoursename () {returnCoursename; }     Public voidsetcoursename (String coursename) { This. Coursename =Coursename; }     PublicInteger GetCode () {returnCode; }     Public voidSetcode (Integer code) { This. Code =Code; }}
 Public classTeacher {PrivateString TeacherName; PrivateInteger Teacherage; PrivateCourse Course; PrivateList<student>students;  PublicString Getteachername () {returnTeacherName; }     Public voidsetteachername (String teachername) { This. TeacherName =TeacherName; }     PublicInteger getteacherage () {returnTeacherage; }     Public voidsetteacherage (Integer teacherage) { This. Teacherage =Teacherage; }     PublicCourse GetCourse () {returncourse; }     Public voidSetcourse (Course Course) { This. course =course; }     PublicList<student>getstudents () {returnstudents; }     Public voidSetstudents (list<student>students) {         This. Students =students; }}

The conversion between JSON string and JavaBean is recommended to use the Typereference<t> class, the use of generics can be more clear, of course, there are other ways of conversion, this is not discussed here.

Example 2.1-json string-conversion between a simple object type and a JavaBean

 /**   * JSON string-conversion between a simple object and Javabean_obj 
    */ static  void   Testjsonstrtojavabeanobj ( {Student Student  = Json.parseobject (json_obj_str, new  TYPEREFERENCE&L T        Student> () {});  // student student1 = Jsonobject.parseobject (Json_obj_str, New typereference<student> () {});  //  Because Jsonobject inherits JSON, so it's also possible   System.out.println (Student.getstudentname ()  +": "+student.getstudentage ()); }

Example 2.2-json string-conversion between array type and JavaBean

/*** JSON string-conversion between array type and Javabean_list*/     Public Static voidtestjsonstrtojavabeanlist () {ArrayList<Student> students = Json.parseobject (JSON_ARRAY_STR,NewTypereference<arraylist<student>>() {}); //arraylist<student> students1 = Jsonarray.parseobject (json_array_str, New typereference<arraylist< Student>> () {});//because Jsonarray inherits the JSON, so it's also possible.                 for(Student student:students) {System.out.println (Student.getstudentname ()+":"+student.getstudentage ()); }    }

Example 2.3-the conversion between a complex JSON format string and a JavaBean

    /*** Conversion between complex JSON format strings and Javabean_obj*/     Public Static voidTestcomplexjsonstrtojavabean () {Teacher Teacher= Json.parseobject (Complex_json_str,NewTypereference<teacher>() {}); //Teacher teacher1 = Json.parseobject (complex_json_str, New typereference<teacher> () {});//because Jsonobject inherits the JSON, so it's also possible.String TeacherName =Teacher.getteachername (); Integer Teacherage=Teacher.getteacherage (); Course Course=Teacher.getcourse (); List<Student> students =teacher.getstudents (); }

For Typereference<t>, because its construction method is decorated with protected, the subclass of its intern class is used when creating its object under other packages: New Typereference<teacher> () {}

In addition:

1, for the JSON object and JSON format string conversion can be directly used tojsonstring () this method.

The conversion between the 2,javabean and the JSON format string is to be used: json.tojsonstring (obj);

The conversion between 3,javabean and JSON objects uses: Json.tojson (obj), and then uses the coercion type conversion, jsonobject, or Jsonarray.

To conclude, we, as programmers, are going to go into a little bit of a thorough study of the problem. When you have a thorough understanding of the principle, development is also handy, a lot of development problems and doubts will be solved, and in the face of other problems can also be done comprehend by analogy. Of course, in the development of not too much time to let you study the principle of development in order to achieve the premise of the function, you can wait for the project on-line, you have a lot of time or spare time, you can go to the inquisitive, in-depth study of a technology, in order to think this is a programmer's growth is very important thing.

Fastjson conversion between JSON-formatted strings, JSON objects, and JavaBean

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.