Java parsing JSON string--single entity

Source: Internet
Author: User

The most basic JSON string:

{
    "age": "
    Gender": "Male",
    "Grades": "Class three",
    "name": "Susan",
    "weight": 63.5
}

The top is a very basic JSON string, and when we see this string we have to think about how to parse the JSON string and what kind of entity class we're going to put the information into after parsing.

first , because the outermost layer of JSON uses the "{}" braces, we can tell that the outermost layer we need is a class, not an array or a list. So we define a class to correspond to it, Student.java.

Next , we analyze the attribute elements in this JSON string. Age corresponds to an integer 20, then we define a private shape member variable in the student class; Age,gender, grades, and name correspond to a string type. We also define the three private string member variables accordingly; weight the corresponding value is a floating-point type with a decimal number, then we define a private float type member variable. (the name of the defined member variable is best the same as the name of the element in the JSON string, so that when we go through the class to turn the JSON string, it's a good match).

then we generate the Get/set method for all the member variables.

the Student.java we generate are as follows:

Package Com.bean;

/**
 *  student/public
class Student {

    private int age;//age
    private String gender;//sex, male/ Female
    private String grades;//class
    private string name;//name
    private float weight;//weight public

    int Getage () {return age
        ;
    }
    public void Setage (int age) {
        this.age = age;
    }
    Public String Getgender () {return
        gender;
    }
    public void Setgender (String gender) {
        this.gender = gender;
    }
    Public String Getgrades () {return
        grades;
    }
    public void Setgrades (String grades) {
        this.grades = grades;
    }
    Public String GetName () {return
        name;
    }
    public void SetName (String name) {
        this.name = name;
    }
    public float Getweight () {return
        weight;
    }
    public void Setweight (float weight) {
        this.weight = weight;
    }

}

Now we're going to parse the JSON string content and put it in the student entity class:

The first approach is to turn the JSON string into student directly through Jsonobject.

Package com.test;

Import Net.sf.json.JSONObject;

Import com.bean.Student;

public class Domain {public

    static void Main (string[] args) {

        String jsonstr = "{\ age\": 20,\ "gender\": \ "Male\", \ "Grades\": "Three Shifts", "name\": \ "Susan \", "Weight\": 63.5} ";

        Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);

        Student stu = (Student) Jsonobject.tobean (Jsonobject, student.class);

        System.out.println (Stu.getname ());

    }

Description: This method requires the same member variable name in the class as the element name in the JSON string; The member variable in the Student class must have a set method. Because Jsonobject assigns the value of an element in a JSON string to a variable in the student class through the Tobean method, the Set method is used to assign the value. This also explains why the names in 1 are the same; When the student class has a few more member variables in the JSON string, or if the JSON string has more elements that are not in the student class, the program does not give an error, but when the values are parsed, Will not be parsed into our student class. If the type of the member variable in the class is not consistent with the type of the JSON string, it is also possible that the value cannot be resolved, such as the age value is the string "abc", and the int age member variable in the class is not receiving a value.

The second method: get the values of each element from Jsonobject

Package com.test;

Import Net.sf.json.JSONObject;

public class Domain {public

    static void Main (string[] args) {

        String jsonstr = "{\ age\": 20,\ "gender\": \ "Male\", \ "Grades\": "Three Shifts", "name\": \ "Susan \", "Weight\": 63.5} ";

        Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);

        int age = Jsonobject.getint (' age ');
        String gender = jsonobject.getstring ("gender");
        String grades = Jsonobject.getstring ("grades");
        String name = jsonobject.getstring ("name");
        float weight = (float) jsonobject.getdouble ("Weight");

        System.out.println (age);
        SYSTEM.OUT.PRINTLN (gender);
        System.out.println (grades);
        SYSTEM.OUT.PRINTLN (name);
        SYSTEM.OUT.PRINTLN (weight);

    }

Description: This method does not require the same variable name we define as the element name in the JSON string, such as we can also string studentname = jsonobject.getstring ("name"); If the element we are taking does not exist in the JSON string, it will be an error; If we take a different type of element than the received type, we may be able to make an error;

The third method: iterative output with iterators

Package com.test;

Import Java.util.Iterator;

Import Net.sf.json.JSONObject;

public class Domain {

    @SuppressWarnings (' rawtypes ') public
    static void Main (string[] args) {

        String jsonstr = "{\" age\ ": 20,\" gender\ ": \" Male\ "," grades\ ": \" three shifts \ "," name\ ": \" Susan \ "," Weight\ ": 63.5}";

        Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);

        iterator keys = Jsonobject.keys ();

        String key = null;
        Object value = null;
        while (Keys.hasnext ()) {
            key = (String) keys.next ();
            Value = Jsonobject.get (key);

            System.out.println ("Key:" +key+ "Value:" +value.tostring ());}}}

Description: With this iteration, all the elements can be acquired; In an iterative way we cannot define the type of value that corresponds to each element in advance.

Finally, let's take a look at how to reverse the student class to generate a JSON string

Package com.test;

Import Net.sf.json.JSONObject;

Import com.bean.Student;

public class Domain {public

    static void Main (string[] args) {

        Student stu = new Student ();

        Stu.setage (a);
        Stu.setgender ("female");
        Stu.setgrades ("one Class");
        Stu.setname ("Lucy");
        Stu.setweight (51.3f);

        String jsonstr = Jsonobject.fromobject (stu). toString ();
        System.out.println (JSONSTR);

    }

the generated string is:

{"Age": "Gender": "Female", "Grades": "Class", "Name": "Lucy", "Weight": 51.3}
Related Article

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.