(1). Resolve one of the object:
Copy Code code as follows:
{"url": "Http://www.cnblogs.com/qianxudetianxia"}
Parsing method:
Copy Code code as follows:
Jsonobject Demojson = new Jsonobject (jsonstring);
String url = demojson.getstring ("url");
(2). Parse Object two:
Copy Code code as follows:
{"Name": "Android", "Name": "iphone"}
Parsing method:
Copy Code code as follows:
Jsonobject Demojson = new Jsonobject (jsonstring);
String name = demojson.getstring ("name");
String Version = demojson.getstring ("version");
System.out.println ("Name:" +name+ ", Version:" +version);
(3). Parse Array One:
Copy Code code as follows:
Parsing method:
Copy Code code as follows:
Jsonobject Demojson = new Jsonobject (jsonstring);
Jsonarray numberlist = Demojson.getjsonarray ("number");
for (int i=0; i<numberlist.length (); i++) {
Because the type in the array is int, Getint is the same as the other Getstring,getlong
System.out.println (Numberlist.getint (i));
}
(4). Parse Array bis:
Copy Code code as follows:
{' Number ': [[1],[2],[3]]}
Parsing method:
Copy Code code as follows:
Nested array traversal
Jsonobject Demojson = new Jsonobject (jsonstring);
Jsonarray numberlist = Demojson.getjsonarray ("number");
for (int i=0; i<numberlist.length (); i++) {
Gets the array in the array
System.out.println (Numberlist.getjsonarray (i). GetInt (0));
}
(5). Parse object and array:
Copy Code code as follows:
{' Mobile ': [{' name ': ' Android '},{' name ': ' iphone '}]}
Parsing method:
Copy Code code as follows:
Jsonobject Demojson = new Jsonobject (jsonstring);
Jsonarray numberlist = Demojson.getjsonarray ("mobile");
for (int i=0; i<numberlist.length (); i++) {
System.out.println (Numberlist.getjsonobject (i). getString ("name"));
}
So, we find that the following is followed by the type of result you want to get: GetType, which is helpful for understanding.
(6). Using Opttype:
In the example above, using GetType throws an exception when it encounters a node that is not found.
If the node is not found with opttype, null or default value is returned.
Copy Code code as follows:
No URL node, throw exception
String url = demojson.getstring ("url");
No URL node, return NULL, return default value if base type
String url = demojson.optstring ("url");
(7). UTF-8 BOM Header causes a problem with JSON exception parsing
When the JSON file is saved as Utf-8, the BOM header "EF BB EF" Byte is generated at the top of the text (which needs to be opened with 16 tools to see) under the Windows platform.
There are two ways to fix this:
A. Use UltraEdit to open the JSON file, save as the time, select Format UTF-8, no BOM header, if not, in Notepad open, save as UTF-8 under, try a few more on it.
B. Using code processing to intercept the JSON body content:
Copy Code code as follows:
String jsonstring = getjsonstring ();
jsonstring = jsonstring.substring (Jsonstring.indexof ("{"), Jsonstring.lastindexof ("}") +1);