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

Source: Internet
Author: User

Maven dependencies that need to be introduced

<!--Fastjson Start -<Dependency>     <groupId>Com.alibaba</groupId>     <Artifactid>Fastjson</Artifactid>     <version>1.1.37</version></Dependency><!--Fastjson End -

    • 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 type private static final String  json_obj_str = "{\" studentname\ ": \" lily\ ", \" studentage\ ": 12}";// JSON string-array type private static final String  json_array_str = "[{\" studentname\ ": \" lily\ ", \" studentage\ ": 12},{\" Studentname\ ": \" lucy\ ", \" studentage\ ": 15}]";///complex format JSON string private static final string  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

/***/
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 void Testjsonstrtojsonarray () {        Jsonarray Jsonarray = Json.parsearray (JSON_ARRAY_STR);        Jsonarray jsonArray1 = Jsonarray.parsearray (JSON_ARRAY_STR);//Because Jsonarray inherits JSON, so it is also possible        //Traversal mode 1        int Size = Jsonarray.size ();        for (int i = 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 void Testcomplexjsonstrtojsonobject () {        Jsonobject jsonobject = Json.parseobject (COMPLEX_JSON_STR);        Jsonobject JsonObject1 = Jsonobject.parseobject (COMPLEX_JSON_STR);//Because Jsonobject inherits JSON, so this is also a 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 class Student {    private String studentname;    Private Integer studentage;    Public String Getstudentname () {        return studentname;    }    public void Setstudentname (String studentname) {        this.studentname = studentname;    }    Public Integer Getstudentage () {        return studentage;    }    public void Setstudentage (Integer studentage) {        this.studentage = studentage;    }}
public class Course {    private String coursename;    Private Integer code;    Public String Getcoursename () {        return coursename;    }    public void Setcoursename (String coursename) {        this.coursename = coursename;    }    Public Integer GetCode () {        return code;    }    public void Setcode (Integer code) {        this.code = code;    }}
public class Teacher {    private String teachername;    Private Integer teacherage;    Private Course Course;    Private list<student> students;    Public String Getteachername () {        return teachername;    }    public void Setteachername (String teachername) {        this.teachername = teachername;    }    Public Integer Getteacherage () {        return teacherage;    }    public void Setteacherage (Integer teacherage) {        this.teacherage = teacherage;    }    Public Course GetCourse () {        return Course;    }    public void Setcourse (Course Course) {        this.course = Course;    }    Public list<student> getstudents () {        return students;    }    public void Setstudents (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     *    /public static void Testjsonstrtojavabeanobj () {        Student Student = Json.parseobject (JSON_OBJ_STR, New typereference<student> () {});        Student student1 = Jsonobject.parseobject (json_obj_str, New typereference<student> () {});// Because Jsonobject inherits the JSON, it is also possible to        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 void Testjsonstrtojavabeanlist () {                ArrayList <Student> students = Json.parseobject (JSON_ARRAY_STR, New typereference<arraylist<student>> () {});        arraylist<student> students1 = Jsonarray.parseobject (json_array_str, New typereference<arraylist< Student>> () {});//Because Jsonarray inherits JSON, so this is 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 void Testcomplexjsonstrtojavabean () {        Teacher Teacher = Json.parseobject (complex_json_str, New typereference<teacher> () {});        Teacher teacher1 = Json.parseobject (complex_json_str, New typereference<teacher> () {});//Because Jsonobject inherits JSON , so it is also possible to        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, it is used to implement subclasses of the class when it is created 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.

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.