Document directory
- 1. Map
- 2. Array
- 1. simple XML
- 2. Complex XML
- 1. jsonobject code instance
- 2. jsonarray code instance
- 3. nested jsonobject and jsonarray code instances
- 4. Sample jsonstringer code
- Write in complex JSON format
- The above code generates the following JSON format:
- 5. Sample Code of jsontokener
- Summary:
I. Introduction to JSON
JSON (JavaScript Object Notation), similar to XML, is a data exchange format. For example, if Java generates a data to Javascript, JSON can be used in addition to XML;
JSON is easier to express than XML;
Official Website: http://www.json.org/
JSON is X in Ajax (that is, XML can be replaced); ------ From the founder of JSON;
Note: JSON is not a document format, and there is no *. JSON document. Generally, documents in JSON format exist in txt, while XML can be a standard;
Web site for online validation of JSON structure: http://www.bejson.com/go.html? U = http://www.bejson.com/jsonview2/
Ii. JSON Data Structure
JSON has two data structures:
(1) map, also known as an object ;{....}
(2) array; [...]
That is to say, all JSON objects must be expressed in these forms;
1. Map
In short, map in Java is given in the form of name-value pairs. Names and values are separated by ":", and two maps are separated by ",". The general representation is as follows:
{'Key1': 'value1', 'key2': 'value2 '}
The following figure shows the official website:
2. Array
It is an array in the general sense, the general form is as follows:
['Arr1', 'arr2', 'arr3'];
The following figure shows the official website:
The value in the figure can be:
Summary:
(1) there are only two types of JSON data structures;
(2) nested representation, such as nested object in array;
(3) Remember: The object is represented by {}, and the array is represented;
Iii. Examples of conversion between JSON and XML
Any XML mentioned above can be converted into a 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 title="book1" price="$11"/></signing><signing><author name="author-2"/><book title="book2" price="$22"/></signing></section>
JSON format:
"section":{"title":"BOOK","signing":[{"author":{"name":"author-1"},"book":{"title":"book1","price":"$11"}},{"author":{"name":"author-2"},"book":{"title":"book2","price":"$22"}}]}}
Note: attributes in XML are also represented by JSON map;
4. JSON package
If you want to use a JSON package, you can download the source code of the JSON package and add the code to the Eclipse project to call it;
If you want to see the API documentation, see: http://www.JSON.org/java/index.html
The two most common classes in a 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. Sample jsonstringer code
Jsonstringer can be used to quickly construct a JSON text, convert it to a string, and write it into a file;
Jsonstringer is a subclass of jsonwriter;
Jsonstringer is constructed by object (). Key (). Value (). Key (). Value (). endobject;
Object () indicates to start an object, that is, add {;
Endobject () indicates that an object is ended, that is, adding };
Array () indicates to start an array, that is, to add [;
Endarray () indicates to end an array, that is, to add a];
Key () indicates adding a key;
Value () indicates 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);}}
Write in complex JSON format
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.JSONTokener;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. Sample Code of jsontokener
Jsontokener is used to read files in JSON format;
Jsonobject OBJ = new jsonobject (New jsontokener (Java. Io. Reader); a jsonobject can be read from a file;
Jsonarray OBJ = new jsonarray (New jsontokener (Java. Io. Reader); a jsonarray can be read from a file;
1. txt
{'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 jsontokener (New filereader (new file ("1.txt"); system. out. println (obj. getjsonarray ("book "). getstring (1); // you can read book2 }}
Read code in complicated JSON format:
1. txt
{"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 jsontokener (New filereader (new file ("1.txt"); system. out. println (obj. getjsonobject ("section "). getjsonarray ("signing "). getjsonobject (0 ). getjsonobject ("author "). getstring ("name"); // get author-1 }}
Summary:
1 in Java, strings in JSON format should be represented by single quotation marks;
2. jsonobject + jsontokener can be used to read JSON file objects;
3. printwriter + jsonstringer can be used to write JSON files;
Note: The original attempt to write data with jsonwriter is unsuccessful. Therefore, only jsonstringer + printwriter can be used to write data;