java explanation -- JOSN analysis

JSON syntax

1. Function: JSON text is a medium similar to XML text file used to store and transfer data information
Note: like XML, json can be used not only as a data carrier through response files, but also as a corresponding data carrier through strings satisfying syntax, which is called "json string"

2. Data storage in JSON adopts {} and [] syntax
{} – > double column set (Dictionary) in Java
[] – > single column set (array) in Java

3. The top level of JSON syntax is single {} or single []

4. The structure in JSON syntax is {} [] nested with each other ({} can be nested with {} [] / [] or {} [])

5. Comma (,) is used as the identification of field segmentation in JSON syntax
Note: comma cannot be added to the last field

6. The syntax in the dictionary is {"key": value} format
Note: key is the string value with type
Syntax of multiple statements:
{
"key1" : value1,
"key2" : value2,
"key3" : value3,
"...." : ......,
"keyn" : valuen
}

7. The edge syntax in the array is [value1, Value2 , value n] format
Note: value has type

8. Each value in {} and [] can be {} / [] and multiple value types may not be the same

Code example:
Person.json:

{
    "name" : "Aunt Li",
    "gender" : "female",
    "age" : 30
}

Car.json:

[
    {
        "id" : "001",
        "brand" : "BMW",
        "color" : "silvery",
        "size" : 5
    },

    {
        "id" : "002",
        "brand" : "T",
        "color" : "white",
        "size" : 2
    },

    {
        "id" : "003",
        "brand" : "F1",
        "color" : "Red",
        "size" : 1
    }
]

School.json:

{
    "status" : 0,
    "msg" : "json cambridge college ",
    "data" :
    [
        {
            "tag" : "Teachers",
            "data" : 
            [
                {
                    "name" : "Teacher1",
                    "gender" : "male",
                    "subject" : "Art",
                    "salary" : 800
                },
                {
                    "name" : "Teacher2",
                    "gender" : "female",
                    "subject" : "Fine Arts",
                    "salary" : 2000
                },
                {
                    "name" : "Teacher3",
                    "gender" : "Unknown",
                    "subject" : "Biology",
                    "salary" : 2100
                }
            ]
        },
        {
            "tag" : "Students",
            "data" : 
            [
                {
                    "name" : "Student1",
                    "gender" : "male",
                    "age" : 18,
                    "class" : "Class three"
                },
                {
                    "name" : "Student2",
                    "gender" : "male",
                    "age" : 8,
                    "class" : "Class six"

                },
                {
                    "name" : "Student3",
                    "gender" : "female",
                    "age" : 16,
                    "class" : "Class eight"
                },
                {
                    "name" : "Student4",
                    "gender" : "female",
                    "age" : 10,
                    "class" : "Class seven"

                }
            ]
        }
    ]
}

All methods are encapsulated. Please check carefully:

public class practice {
    public static void main(String[] args) {
        // JSON parsing
        //fun1("[1,2,3,4,5,false,\"true\"]");

        // Two cases of JSON parsing
        //fun2("{\"color \ ": \" red \ ", \" weight \ ": 2.2}");

        // JSON parsing: a mixture of two situations
        //Fun3 ("{" data ": [1,2,3,4,5]," name \ ":" Zhang San \ "}");

        // Convert json to object
//      String jstring = jsonstring ("path of person. JSON");
//      
//      Person p = JSON.parseObject(jString, Person.class);
//      System.out.println(p);

        // Get the data of the car
//      String jstr = jsonstring ("path of car. JSON");
//      
//      System.out.println(car1(jStr));
//      System.out.println(car2(jStr));
//      System.out.println(car3(jStr));

        Map school = Analy.jsonToMap();
        System.out.println("school:\n" + school);
    }

    // JSON parsing 
    private static void fun1(String string) {
        Object object = JSON.parse(string);
        System.out.println(object);

        // Downward Transformation: downward transformation of object s into other types
        JSONArray jArray = (JSONArray)object;
        int num = jArray.getIntValue(0);
        boolean b = jArray.getBooleanValue(5);
        System.out.println(num);
        System.out.println(b);
    }

    // Two cases of JSON parsing
    private static void fun2(String string) {
        Object object = JSON.parse(string);
        // JSON string resolves to JSONObject object with {} package
        // JSON string resolves to JSONArray object with [] package
        JSONObject jObject = (JSONObject)object;
        // JSONObject index data with key
        // JSONArray is the following index data
        String color = jObject.getString("color");
        System.out.println(color);
        double weight = jObject.getDoubleValue("weight");
        System.out.printf("%.1f", weight);
    }

    // JSON parsing: a mixture of two situations
    private static void fun3(String string) {
        Object object = JSON.parse(string);

        JSONObject jObject = (JSONObject) object;
        JSONArray array = jObject.getJSONArray("data");
        System.out.println(array);

        for (Object obj : array) {
            System.out.print(obj + " ");
        }
        System.out.println();

        for (int i = 0; i < array.size(); i++) {
            int num = array.getIntValue(i);
            System.out.print(num + " ");
        }
        System.out.println();

        // New integer [] {}: an object of an array of type integer
        // toArray: an object that requires an array of objects as a parameter to determine generics
        Integer[] integer = array.toArray(new Integer[]{}); 
        for (Integer i : integer) {
            System.out.print(i + " ");
        }
        System.out.println();

        String name = jObject.getString("Full name");
        System.out.println(name);
    }

    // Convert JSON text files to JSON strings
    /*
     * analysis:
     * BufferedReader One line read file
     * StringBuffer Splicing the read files over and over again
     * Return the final string
     */
    public static String jsonString(String filePath) {
        // Create StringBuffer
        StringBuffer sb = new StringBuffer();
        // Create BufferedReader
        BufferedReader reader = null;
        try {
            File file = new File(filePath);

            reader = new BufferedReader(new FileReader(file));

            String In = "";
            while ((In = reader.readLine()) != null) {
                sb.append(In.trim());// To blank
            }
        } catch (Exception e) {
            System.err.println("json File parsing failed" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.println("Stream close failed" + e.getMessage());
            }
        }
        return new String(sb);
    }

    // Get the data of the car
    // 1 getJSONObject / parseObject(toJSONString() , class) / 
    private static Car car1(String jsonString) {
        Object object = JSON.parse(jsonString);
        JSONArray jArray = (JSONArray)object;
        JSONObject jObject = jArray.getJSONObject(0);
        Car car = JSON.parseObject(jObject.toJSONString(), Car.class);
        return car;
    }

    // 2 getJSONObject() / toJavaObject()
    private static Car car2(String jsonString) {
        Object object = JSON.parse(jsonString);
        JSONArray jArray = (JSONArray)object;
        JSONObject jObject = jArray.getJSONObject(1);
        Car car = JSON.toJavaObject(jObject, Car.class);
        return car;
    }

    // 3 put it directly into the collection and get the elements
    private static Car car3(String jsonString) {
        // JSON / JSONArray / JSONObject can be used
        List<Car>  cars = JSON.parseArray(jsonString, Car.class);
        Car car = cars.get(2);
        return car;
    }
}

/*
 * Function: provide a common JSON parsing result externally
 * Reason for defining single instance: public encapsulation / single instance
 */
class Analy{
    // Provide a single object to the outside world
    public static Map school = null;

    // The object provided to the outside world has nothing to do with its own object
    // No external constructor is provided and no operation is done by the self constructor
    public Analy() {}

    // Singleton method provided by singleton - do unique object assignment
    // Analysis of JSON file as Map assignment operation corresponding to unique object school
    public static Map jsonToMap() {
        if (school == null) {
            school = analyse();
        }
        return school;
    }

    // analytic method 
    private static Map analyse() {
        Map map = new HashMap<>();
        String jStr = practice.jsonString("School.json Path to");
        // first floor
        JSONObject jsonObject = JSON.parseObject(jStr);
        // The second floor
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        // Tier 3 Teachers / Students
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jObj = jsonArray.getJSONObject(i);
            // Tier 4 Teacher array. Student array
            JSONArray jArray = jObj.getJSONArray("data");
            String tag = jObj.getString("tag");
            // The fifth layer is analyzed as a whole as list < teacher > / list < student >
            if (tag.equals("Teachers")) {
                List<Teacher> ts = JSON.parseArray(jArray.toJSONString(), Teacher.class);
                map.put(tag, ts);
            }
            if (tag.equals("Students")) {
                List<Student> ss = JSON.parseArray(jArray.toJSONString(), Student.class);
                map.put(tag, ss);
            }
        } 
        return map;
    }
}

Tags: JSON xml Java

Posted on Fri, 01 May 2020 22:48:33 -0700 by blkraven