JAVA - parse JSON from the file and write it to the JSON file (details)

Keywords: Java JSON less xml

1.json introduction

json is less descriptive than XML, but its data volume is smaller and its transfer speed is faster

The writing format of json data is "Name: value pair", for example:

"Name" : "John"                        //name For name,The value pairs are"john"Character string

The value pair types are divided into:

  • Number (integer or floating point)
  • String (in double quotes)
  • Logical value (true or false)
  • Array (in brackets [])
  • Object (in curly braces {})
  • null

 

Of course, an array can also contain multiple objects:

{
    "employees": [
        { "Name":"John" , "Age":19 },
        { "Name":"Anna" , "Age":22 },
        { "Name":"Peter", "Age":23 }
    ]
}

Represents that there are three object arrays in the "employees" object (each object array represents an employee information), and the data in parallel must be separated by commas "," and "

 

2.json package usage

Many JAVA based JSON parsing tools (including C/C + + and other related tools) have been published on www.json.org. Among them, org.json and JSON lib are relatively simple, and they are similar in use. Here we use org.json, the download address of org.json is: https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav

 

3.json analysis

3.1 analysis steps

  • First, construct a json object through the new JSONObject(String), and pass in the json string
  • Then get the corresponding value through getXXX(String key) method

3.2 example.json example file is as follows:

{
    "FLAG": 1,
    "NAME": "example",
    "ARRAYS":
    [
        {
            "Name":       "array1",
            "String":     "Ha ha DA 1"
        },
        {
            "Name":       "array2",
            "String":     "Ha ha Da 2"
        },
        {
            "Name":       "array3",
            "String":     "Ha ha Da 3"
        },
        {
            "Name":       "array4",
            "String":     "Ha ha Da 4"
        }
    ]
}

3.3 the resolution code is as follows:

@Test

    public void JsonParser() throws Exception{

        char cbuf[] = new char[10000];
        InputStreamReader input =new InputStreamReader(new FileInputStream(new File("src//example.json")),"UTF-8");
        int len =input.read(cbuf);
        String text =new String(cbuf,0,len);
        //1.Construct a json object
        JSONObject obj = new JSONObject(text.substring(text.indexOf("{")));   //Filter read utf-8 First three label bytes,from{Start reading

        //2.adopt getXXX(String key)Method to get the corresponding value
        System.out.println("FLAG:"+obj.getString("FLAG"));
        System.out.println("NAME:"+obj.getString("NAME"));

        //Get array
        JSONArray arr = obj.getJSONArray("ARRAYS");
        System.out.println("Array length:"+arr.length());
        for(int i=0;i<arr.length();i++)
        {
            JSONObject subObj = arr.getJSONObject(i);
            System.out.println("array Name:"+subObj.getString("Name")+" String:"+subObj.getString("String"));
        }

    }

Print as follows:

 

 

4. Write json file

4.1 write json steps

  • First, construct an empty json object through new JSONObject()
  • If you want to write single object content, write it through jsonobject. Put (key, value)
  • If you want to write the contents of multiple array objects, write them through jsonobject. Accumulate (key, value)
  • Finally, import the data into the file through jsonobject. Tostring()

 

4.2 write an example as follows:

@Test
    public void JsonWrite() throws Exception{

        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("exampleWrite.json"),"UTF-8");

        JSONObject obj=new JSONObject();//Establish JSONObject object

        obj.put("FLAG","1");for(Integer i=1;i<4;i++)
        {
            JSONObject subObj=new JSONObject();//Create subobjects in an object array
            subObj.put("Name","array"+i);
            subObj.put("String","Xiao Bai"+i);
            obj.accumulate("ARRAYS",subObj);
        }
        System.out.println(obj.toString());

        osw.write(obj.toString());
        osw.flush();//Clear buffer, force output data
        osw.close();//Close output stream
}

Print as follows:

Posted by theycallmepj on Thu, 12 Dec 2019 02:50:55 -0800