Android reads JSON data (traversing Jsonobject and Jsonarray) __json

Source: Internet
Author: User
Tags numeric value jsonviewer
The private String Getjson () {//jsonstring contains, for example, Unicode encoded character \u67ef, automatically converts to the corresponding language character when GetString. The data fragments obtained from the server are generally in the following format/*{"Showid": "38f5ef6ae35711e0a046", "ShowName": "\U996D\U5C40\U4E5F\U75AF\U72C2", "Completed" : 1, "Paid": 1, "ReleaseDate": "2012-01-23", "Episode_total": "1", "Episode_last": "1", "Show_thumburl": "http:\/ \/g4.ykimg.com\/0102641f464f04034a000000000000e09bc52f-62ae-3fa1-e4f0-a62472c09dc0 "," Showcreatetime ":" 2011-09-20 15:07:37 "," showcategory ":" \u7535\u5f71 "," Deschead ":" \u4f20\u8bf4\u4e2d\u7684\u201c\u5929\u4eba\u4e00 \u201d\u996d\u9986\uff0c\u6d77\u9c9c\u8d29\u5b50\u8001\u867e\u7c73\u524d\u6765\u5411\u6b63\u8d70\u9709\u8fd0\ U7684\u5c01\u8001\u677f\u8ba8\u503a\u3002\u4e0e\u6b64\u540c\u65f6\uff0c\u7edd\u8272\u6027\u611f\u7684\u7f8e\ u5973\uff0c\u795e\u79d8\u5a01\u4e25\u7684\u5927\u4eba\u7269\uff0c\u8fc7\u6c14\u7684\u529f\u592b\u660e\u661f\
			uff0c\u56fd\u5b66\u5927\u5e08\uff0c\u66b4\u53d1\u6237, \u6d41\u6d6a\u6b4c\u624b\uff0c\u5a01\u4e25\u7684 ... ","Showtotal_comment": "583", "reputation": "8.335", "SHOWTOTAL_VV": "2952956", "Show_vthumburl": "Http:\/\/g3.ykimg.co m\/0102641f464f10c6cf0000000000001078aa2c-3507-7a46-ac81-15fbcec1a241 "," movie_genre ": [" \u559c\u5267 "," \u5267\ U60c5 "]," area ": [" \u5927\u9646 "]," performer ": [{" id ":" 12657 "," name ":" \u5218\u6866 "," character ": [" \u5c01\u800 1\u677f "]}, {" id ":" 14685 "," name ":" \u8303\u4f1f "," character ": [" \u8c2d\u5927\u5e08 "]}, {" id ":" 186154 "," Nam E ":" \u9ec4\u6e24 "," character ": [" \u5bb6\u660e "]}, {" id ":" 21889 "," name ":" \U83AB\U5C0F\U68CB "," character ": [" \u 83ab\u59ae\u5361 "]}, {" id ":" 17725 "," name ":" \u4ee3\u4e50\u4e50 "," character ": [" \u5c0f\u8774\u8776 "]}, {" id ":" 1 
			5808 "," name ":" \u6881\u51a0\u534e "," character ": [" \u8001\u6885 "]}, {" id ":" 17853 "," name ":" \u97e9\u7ae5\u751f ", "Character": ["\u5927\u8001\u603b"]}, {"id": "16635", "name": "\u5218\u4e9a\u6d25", "character": ["\u8521\u7259\u
	91d1 "]}, {" id ":" 161699 ",		"Name": "\u51af\u74c5", "character": ["\u72d7\u72d7"]}, {"id": "228705", "name": "\u5df4\u591a", "character": ["\ U8001\u867e\u7c73 "]}]," Firstepisode_videourl ":" http:\/\/v.youku.com\/v_show\/id_xmzu4mta3mjc2.html "," Showlink " : "http:\/\/www.youku.com\/show_page\/id_z38f5ef6ae35711e0a046.html", "Quality": "\u8d85\u6e05"},*/String
		jsonstring = "{\ flag\": \ "flag\", \ "message\": \ "Success\", \ "name\": [{\ "name\": \ "Jack\"},{\ "name\": \ "Lucy\"}]} ";
			try {log.d ("Debugtest", "jsonstring--" +jsonstring);
			Jsonobject result = new Jsonobject (jsonstring);//Convert to Jsonobject//int num = Result.length ();
			Jsonarray namelist = Result.getjsonarray ("name");//Get jsonarray int length = Namelist.length ();
			String AA = "";
				for (int i = 0; i < length; i++) {//traverse jsonarray jsonobject OJ = Namelist.getjsonobject (i);
				AA = AA + oj.getstring ("name") + "|";
			LOG.D ("Debugtest", integer.tostring (i) + "aa--" +AA);
			Iterator<?> it = Result.keys (); String Aa2= "";
			String bb2 = null;
				while (It.hasnext ()) {//traverse jsonobject BB2 = (String) it.next (). toString ();
				AA2 = Aa2 + result.getstring (BB2);
			LOG.D ("Debugtest", bb2+ "--" +aa2);
			} log.d ("Debugtest", "Aa2--" +aa2);
		return AA;
		catch (Jsonexception e) {throw new RuntimeException (e); /*log results: D/debugtest (4291): jsonstring--{"FLAG": "FLAG", "message": "SUCCESS", "name": [{"Name": "Jack"},{"name": "
		Lucy "}]} d/debugtest (4291): 0 aa--jack|
		D/debugtest (4291): 1 aa--jack|lucy| D/debugtest (4291): FLAG--FLAG d/debugtest (4291): Message--flagsuccess d/debugtest (4291): Name--flagsuccess[{" Name ":" Jack "},{" name ":" Lucy "}] D/debugtest (4291): Aa2--flagsuccess[{" name ":" Jack "},{" name ":" Lucy "}]*/}


The definition of JSON:

A lightweight data interchange format with good readability and fast-coding features. The industry's mainstream technology provides it with a complete solution (a bit like regular expressions that are supported by most languages today), allowing data exchange between platforms. JSON uses a highly compatible text format, as well as behavior similar to the C language system. –json.org

Why use JSON.

It's simple, because it's 10 times times faster than XML.

What are the application cases?

The open APIs of companies such as Twitter, watercress, Facebook, and so on, typically offer a variety of formats for developers to choose (XML, JSON, Atom, and so on), while at the end of the phone we naturally want to give the user the best experience, so I choose the most efficient JSON format.

According to my document habits, will be accompanied by a specific demo, at the end of this document can be found in the download, where the example is the Watercress API.

The structure of JSON:

Name/value pairs similar to the familiar keyed list, Hash table, disctionary, and associative array. There is another class "Bundle" in the Android platform that has similar behavior in some ways.
Org.json.JSONObject Array, a set of ordered lists of data. Org.json.JSONArray

JSON-related classes in Android (4) and exceptions (1):

L Jsonarray

L Jsonobject

L Jsonstringer

L Jsontokener

L Jsonexception

Jsonobject:

This is the basic unit of the system for the JSON definition, which contains a pair of key/value values. Its response to an external (External: The value of the output of the application ToString () method) is reflected as a standard string (for example: {"JSON": "Hello, World"}, wrapped in curly braces, where key and value are separated by a colon ":"). It has a slight operational format for internal (Internal) behavior, such as initializing a Jsonobject instance, and referencing the internal put () method to add a value: New Jsonobject (). Put ("JSON", "Hello, world!"), The key and value are separated by commas ",".

The types of value include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

There are two different methods of taking values:

Get (): used under conditions that determine the existence of a value, or a exception message will be thrown if the associated key cannot be retrieved.

Opt (): This method is relatively flexible and will return a default value when the specified value cannot be obtained, and will not throw an exception.

Jsonarray:

It represents a set of ordered values. The form of converting it to string output (toString) is wrapped in square brackets, with values separated by commas "," (for example, [Value1,value2,value3], where you can use the short code to get a more intuitive understanding of its format). The interior of this class also has query behavior, and both the Get () and opt () methods can return the specified value through the index index, and the put () method is used to add or replace the numeric value.

The value type of the same class can include Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

Jsonstringer:

According to the official explanation, this class can help create JSON text quickly and easily. The biggest advantage of this is that you can reduce the error in the format resulting in a program exception, referencing this class can automatically create JSON text strictly according to the JSON syntax rules (syntax rules). Only one JSON text can be created for each Jsonstringer entity.

Follow the example below to learn more about: string myString = new Jsonstringer (). Object ()

. Key ("AR"). Value ("www.androidres.com!")

. EndObject ()

. toString ();

The copy code result is a standard set of JSON text:{"AR": "www.androidres.com!"}

The. Object () and. EndObject () must be used at the same time to add boundaries to the values according to the object criteria. Similarly, there is a standard set of methods for arrays to generate boundaries. Array () and. Endarray ().

Jsontokener:

This is the class that the system parses the JSON source string for the Jsonobject and Jsonarray constructors, and it can extract numeric information from the source string.

Jsonexception:

Is the exception information thrown by the Json.org class.

A handy tool jsonviewer

JSON's data format is less readable, but with this tool you can see its data structure clearly.

Official Address http://jsonviewer.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=5432

Software operation is very simple, a screenshot, we will understand.

Attachment: 1.jpg

Attached to the Jsondemo

Take a look at the screenshot first

Attachment: 2.jpg

Code download

Where Jsondemo.zip is the demo code; Jsonview.zip is the auxiliary view gadget Jsonviewer,

Use to view "JSON-formatted data returned from watercress".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.