1. Introduction to JSON
JSON (JavaScript Object Notation), similar to XML, is a data exchange format. For example, if Java generates a data to JavaScript, in addition to using XML, you can also use JSON;
The advantage of JSON over XML is that it is very simple to express; official website: http://www.json.org/
JSON is X in AJAX (that is, it can replace XML); ------From the founder of JSON;
Note: JSON is not a document format, there are no *.json documents. Generally, JSON format documents are found in txt, and XML can be a standard;
json online editor: http://tools.VeVB.COM/tools/json/json_editor.htm
2. JSON data structure
JSON has two data structures:
(1) Map, also known as object; {......}
(2)Array; [......]
That is to say, all JSON objects should be represented in these forms;
1.Map
Simply put, it is a map in Java. The name-value pair is given, and the name and value are separated by ":" and the two maps are separated by "," and the general representation is as follows:
{'key1':'value1','key2':'value2'}
The following is the official website picture:
2.Array
It is an array in the ordinary sense, with the general form as follows:
['arr1','arr2','arr3'];
The following is the official website picture:
The value in the figure can be:
Summarize:
(1) There are only two types of data structures in JSON;
(2) It can be nested, such as Objects can be nested in Array;
(3) Remember: Object is represented by {}, and Array is represented by [ ];
3. Example of JSON and XML conversion
Any XML mentioned above can be converted into JSON package;
1. Simple XML
XML format:
<person> <name>xiazdong</name> <age>20</age> </person>
JSON format:
{ "name":"xiazdong", "age":20 }2. Complex XML
XML format:
<section> <title>BOOK</title> <signing> <author name="author-1"/> <book price="$11"/> </signing> <signing> <author name="author-2"/> <book price="$22"/> </signing> </section>
JSON format:
"section":{ "title":"BOOK", "signing":[ { <span style="white-space:pre"> </span> "author": { "name":"author-1" }, "book": { "title":"book1", "price":"$11" } }, { "author": { "name":"author-2" }, "book": { "title":"book2", "price":"$22" } } <span style="white-space:pre"> </span> ]} }Note: The properties in XML are also represented by JSON's Map;
4. JSON package
If we want to use JSON package, we can download the source code of the JSON package and add these codes to the Eclipse project and call it;
If you want to see the API documentation, you can see: http://www.JSON.org/java/index.html
The two most commonly used classes in the JSON package are JSONObject and JSONArray, which represent two data structures respectively;
1. JSONObject code instance
package com.xiazdong.json; import weibo4j.org.json.JSONArray; import weibo4j.org.json.JSONObject; public class Test { public static void main(String[] args) throws Exception{ JSONObject jsonobj = new JSONObject("{'name':'xiazdong','age':20}"); String name = jsonobj.getString("name"); int age = jsonobj.getInt("age"); System.out.println(name+":"+age); } }2. JSONArray code instance
JSONArray array = new JSONArray(String str); //Convert String to JSONArrayint length = array.length(); //Return the length of Array;
package com.xiazdong.json; import weibo4j.org.json.JSONArray; import weibo4j.org.json.JSONObject; public class Test { public static void main(String[] args) throws Exception{ JSONArray jsonarray = new JSONArray("[{'name':'xiazdong','age':20},{'name':'xzdong','age':15}]"); for(int i=0;i<jsonarray.length();i++){ String name = jsonarray.getJSONObject(i).getString("name"); int age = jsonarray.getJSONObject(i).getInt("age"); System.out.println("name="+name); System.out.println("age="+age); } } } 3. Nested JSONObject and JSONArray code instances
package com.xiazdong.json; import weibo4j.org.json.JSONArray; import weibo4j.org.json.JSONObject; public class Test { public static void main(String[] args) throws Exception{ String str = "{'name':'xiazdong','age':20,'book':['book1','book2']"; JSONObject obj = new JSONObject(str); System.out.println(obj.getJSONArray("book").getString(0)); } }4. JSONStringer code example
JSONStringer can be used to quickly build a JSON format text and convert it into a String, which can be written to a file;
JSONStringer is a subclass of JSONWriter;
JSONStringer is generally constructed through object().key().value().key().value().endObject();
object() indicates that an object is started, that is, adding {;
endObject() indicates that an object is ended, that is, adding };
array() indicates that an array is started, that is, adding a [ ;
endArray() indicates that an array is ended, that is, adding one];
key() means adding a key;
value() means adding a value;
package com.xiazdong.json; import weibo4j.org.json.JSONStringer; public class JsonStringerDemo { public static void main(String[] args) throws Exception{ JSONStringer stringer = new JSONStringer(); String str = stringer.object().key("name").value("xiazdong").key("age").value(20).endObject().toString(); System.out.println(str); } } Complex JSON format writing
package com.xiazdong.json; import java.io.File; import java.io.FileReader; import weibo4j.org.json.JSONArray; import weibo4j.org.json.JSONObject; import weibo4j.org.json.JSONStringer; import weibo4j.org.json.JSONStringer; import weibo4j.org.json.JSONTKENER; public class JsonStringerDemo { public static void main(String[] args) throws Exception{ JSONStringer js = new JSONStringer(); JSONObject obj2 = new JSONObject(); JSONObject obj3 = new JSONObject(); JSONObject obj4 = new JSONObject(); obj4.put("title", "book1").put("price", "$11"); obj3.put("book", obj4); obj3.put("author", new JSONObject().put("name", "author-1")); JSONObject obj5 = new JSONObject(); JSONObject obj6 = new JSONObject(); obj6.put("title", "book2").put("price", "$22"); obj5.put("book", obj6); obj5.put("author", new JSONObject().put("name", "author-2")); JSONArray obj7 = new JSONArray(); obj7.put(obj3).put(obj5); obj2.put("title","BOOK"); obj2.put("signing", obj7); js.object().key("session").value(obj2).endObject(); System.out.println(js.toString()); PrintWriter out = new PrintWriter(new FileOutputStream(1.txt)); out.println(js.toString()); } } The above code generates the following JSON format:
{"section":{ "title":"BOOK", "signing":[ { "author": { "name":"author-1" }, "book": { "title":"book1", "price":"$11" } }, { "author": { "name":"author-2" }, "book": { "title":"book2", "price":"$22" } } ]} } }5.JSONTOkener code example
JSONTOkener is used to read files in JSON format;
JSONObject obj = new JSONObject( new JSONTokener(java.io.Reader)); You can read a JSONObject from a file;
JSONArray obj = new JSONArray( new JSONArray(java.io.Reader)); You can read a JSONArray from a file;
{ 'name':'xiazdong', 'book':['book1','book2'] } package com.xiazdong.json; import java.io.File; import java.io.FileReader; import weibo4j.org.json.JSONObject; import weibo4j.org.json.JSONTOkener; public class JsonStringerDemo { public static void main(String[] args) throws Exception{ JSONObject obj = new JSONObject(new JSONObject(new JSONTokener(new FileReader(new File("1.txt")))); System.out.println(obj.getJSONArray("book").getString(1)); //Can read book2 } } Reading code in complex JSON format:
{"section":{ "title":"BOOK", "signing":[ { "author": { "name":"author-1" }, "book": { "title":"book1", "price":"$11" } }, { "author": { "name":"author-2" }, "book": { "title":"book2", "price":"$22" } } ]} } } package com.xiazdong.json; import java.io.File; import java.io.FileReader; import weibo4j.org.json.JSONObject; import weibo4j.org.json.JSONTOkener; public class JsonStringerDemo { public static void main(String[] args) throws Exception{ JSONObject obj = new JSONObject(new JSONObject(new JSONTokener(new FileReader(new File("1.txt")))); System.out.println(obj.getJSONObject("section").getJSONArray("signing").getJSONObject(0).getJSONObject("author").getString("name")); <span style="white-space:pre"> </span>//Get author-1 } }Summarize:
1 In Java, JSON format String is best represented in single quotes;
2. Use JSONObject+JSONTOkener to read JSON format file objects;
3. Use PrintWriter+JSONStringer to write JSON files;
Note: Since I originally wanted to try to write with JSONWriter, but it was not successful; so I can only use JSONStringer+PrintWriter to write;
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.