First, JSON introduction
JSON (JavaScript Object notation), similar to XML, is a data interchange format, such as Java, which produces a data that wants to be given to JavaScript, and uses JSON in addition to XML;
The advantage of JSON over XML is that it is simple to express; Official website: http://www.json.org/
JSON is an 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, general JSON-formatted documents exist in TXT, and XML can be a standard;
JSON Online Editor: http://tools.jb51.net/tools/json/json_editor.htm
Two, JSON data structure
JSON has two types of data structures:
(1) Map, also known as objects; }
(2) Array;[...]
That is to say, all JSON objects are represented in these forms;
1.Map
Simply put is the map in Java, name-value pairs of the form given, the name and value between ":" Separated by "," between two map separated by "," the general representation is as follows:
{' Key1 ': ' value1 ', ' key2 ': ' value2 '}
The following is the official website chart:
2.Array
is an array of ordinary meanings, the general form is as follows:
[' arr1 ', ' arr2 ', ' arr3 '];
The following is the official website chart:
The value in the figure can be:
Summarize:
(1) There are only two types of JSON data structures;
(2) can be nested representations, such as array can be nested object, etc.;
(3) Remember: object is expressed as {}, array is represented by [];
Three, JSON and XML interchange examples
Any XML mentioned above can be converted into a JSON package;
1. Simple XML
XML format:
<person>
<name>xiazdong</name>
<age>20</age>
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>
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: Attributes in XML are also represented by a map of JSON;
Four, JSON package
If we want to use the JSON package, we can download the source code for the JSON package and add the code to the Eclipse project to invoke it;
If you want to see the API documentation, 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 ':} ');
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); Converts a string to jsonarray
int length = Array.Length ();//Returns the length of the 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 ':}] ';
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 ', ' ': ' 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-formatted text and convert it into a string that can be written to a file;
Jsonstringer is a subclass of Jsonwriter;
Jsonstringer typically is constructed by using the object (). Key (). Value (). Key (). Value (). EndObject ();
Object () indicates the start of an object, that is, add {;
EndObject () indicates that the end of an object is added};
Array () indicates the beginning of an array, that is, to add a [;
Endarray () Indicates the end of an array, that is, adding one];
Key () indicates that a key is added;
Value () indicates that a value is added;
Package Com.xiazdong.json;
Import Weibo4j.org.json.JSONStringer;
public class Jsonstringerdemo {public
static void Main (string[] args) throws exception{Jsonstringer Stringer
= n EW Jsonstringer ();
String str = Stringer.object (). Key ("name"). Value ("Xiazdong"). Key ("Age"). Value. EndObject (). toString ();
System.out.println (str);
}
Complex JSON format write
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.JSONTokener code Example
Jsontokener is used to read JSON-formatted files;
Jsonobject obj = new Jsonobject (new Jsontokener (Java.io.Reader)); You can read a jsonobject from a file;
Jsonarray obj = new Jsonarray (new Jsontokener (Java.io.Reader)); A jsonarray can be read 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 JS Onobject (New Jsontokener (New FileReader ("1.txt")));
System.out.println (Obj.getjsonarray ("book"). GetString (1)); Can read Book2
}
}
Read 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 JSON Object (New Jsontokener (New FileReader ("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 The JSON-formatted string in Java is best expressed in single quotes;
2. Use Jsonobject+jsontokener to read JSON format file objects;
3. Use Printwriter+jsonstringer to write JSON files;
Note: Because originally wanted to attempt to write with Jsonwriter, but did not succeed, so can only use jsonstringer+printwriter write;
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.