JSON Overview
JSON is JavaScript Object Notation, which is a subset of the JavaScript object representation. Have the following characteristics:
Put the data in key-value pairs;
Data is separated by commas;
Braces represent objects;
Square brackets represent arrays.
The value of JSON can be:
Number (integer or floating point number)
String (in dual quotes)
Logic values (True or False)
Array (in the bracket)
Object (in parentheses)
null
JSON's basic grammar
JSON object
JSON objects are written in curly braces, and the objects can contain multiple key-value pairs, for example:
{ "firstName":"John", "lastName":"Doe"}
JSON array
The JSON array is written in square brackets, and the array can contain multiple objects, such as:
{"Employees": [{"firstName": "John", "LastName": "DOE"}, {"firstName": "Anna", "LastName": "Smith"}, {"firstName": "Peter" " , "LastName": "Jones"}]}
In the above example, the curly braces at the root indicate that this is a JSON object, the key of the object is employees, the value is a JSON array, there are 3 JSON objects in this array, and each JSON object is also separated by commas. .
Use Java to read JSON data
We can check the support of various grammar on JSON's official website. For Java, the more mature is Google-Gson.
The Maven depends below:
<Dependency> <GroupId> Com.google.code.gson </Groupid> <Artifactid> GSON </ArtiFactid> <Version> 2.2.4 </Version> </Dependency>
Now write a program to analyze the following test.json:
{"cat": "it", "languages": [{"id": 1, "IDE": "eclipse", "name": "java"}, {"id": 2, "IDE": "" Xcode "," name ":" swift "}, {" id ": 3," IDE ":" Visual Studio "," name ":" c#"}]," pop ": true}
The following code will analyze the above JSON data:
public void readJSON() throws Exception{ // Create a json parser JsonParser parser = new JsonParser(); // Use a parser to parse json data, the return value is JsonElement, and it is forced to convert it into its subclass JsonObject type JsonObj ect object = (jsonObject) parser.parse(new FileReader("test.json")); // Use the get(String memberName) method of JsonObject to return JsonElement, and then use the getAsXXX method of JsonElement to obtain the real type System.out.println( "Cat =" + Object .Get ("Cat"). Getasstring ()); // Traversing the jsonarray languages = object.getAsjsonarray ("Languages"); t laanguage = jsonelement.getasjsonobject (); System.out .println ("ID =" + Language.get ("ID"). Getasint () + ", IDE =" + Language.get ("IDE"). Getasstring () + ", name =" + language.get ( "name"). Getasstring ());} System.out.println ("POP =" + Object.get ("POP"). Getasstring ());}
Use Java to generate json data
The key to generating JSON data is the two methods: ADD and Addproperty in JSON objects. The former is used to add an array or another JSON object to the JSON object, and the latter is used to add attributes to the JSON object. The following code will generate test.json in the above example.
Public Void Createjson () Throws IOEXception {JSONObject Object = New JSONObject (); // Create a JSON object Object.addproperty ("IT"); // Add attributes to JSON objects. JsonArray Languages = New jsonarray (); // Create a jsonObject Language = New JsonObject (); Language.addproperty ("ID", 1); Language.addproperty ("IDE", "Eclipse"); ty ("name", "java"); LANGUAGES.Add (Language); // Add JSON objects to the array to language = new jsonObject (); Language.addproperty ("ID", 2); Language.addproperty ("IDE"), "XCode") ; Language.addproperty ( "name", "swift"); Languages.add (language); Language = new jsonObject (); Language.addproperty ("ID", 3); LANGUAGE.ADDPROPROPRETY ("IDE", "visua" l ranguage. addProperty("name", "C#"); languages.add(language); object.add("languages", languages); // Add array to json object object.addProperty("pop", true ); String jsonStr = object.toString(); // Convert json object into json string PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("data.json"))); pw.print(jsonStr); pw.f lush() ; pw.close();}
In Java, constructing and analyzing JSON I use ORG.JSON. Below is two functions, one is to create JSON, and the other is JSON and analyzed from text constructing JSON.
Create json
//construct json and output it public String jsonTest() throws JSONException{ JSONObject json=new JSONObject(); JSONArray jsonMembers = new JSONArray(); J SonObject Member1 = New JsonObject (); Member1.put ("Loginname", "zhangfan" );; Password, "Userpass"); Member1.put ("Email", "[email protected]"); MEMBER1.PUT ("Sign_date", "2007-06-12"); jsonmembers .put (member1); jsonObject Member2 = New JsonObject (); Member2.put ("Loginname", "ZF"); Member2.put ("Password", "User Pass"); Mail "," 8223939 @qq.com"); member2.put("sign_date", "2008-07-16"); jsonMembers.put(member2); json.put("users", jsonMembers); return json.toString(); }
Analyze json
// Construct JSON from String and Resolve It. Public String JSONTEST2 () Throws jsonexception {String jsonstring = "{/" "users/": [{"loginname":/"zhangfan" /",/" password/":/ "Userpass/",/"email/":/"[email protected]/"}, {/"loginname/":/"zf/",/"password/":/"userpass/",/"email /":"[email protected]/ "}]}"; jsonObject JSON = New JSONObject (jsonstring); jsonarray jsonarray = json.getjsonarray ("Users"); String LoginNames = "LO ginname list: "; for (int i = 0; I <jsonarray.length (); I ++) {jsonObject User = (jsonObject) jsonarray.get (i); string username = (string) user.get ("loginname"); if (i = = jsonarray. length ()-1) {loginnames+= username;} else {loginnames+= username+",";}} Return loginnames;}
It is quite convenient to deal with JSON in Java.