JSON application in Android

Source: Internet
Author: User

JSON definition:
A lightweight data exchange format with good readability and ease of writing. Mainstream technologies in the industry provide a complete solution (somewhat similar to regular expressions)
To exchange data between different platforms. JSON adopts a highly compatible text format and has behaviors similar to the C language system. -Json.org
JSON structure:
Name/value pairs, similar to well-known keyed list, hash table, disctionary, and associative array. On the Android platform, there is another class "bundle", which has similar behavior to some extent. Org. JSON. jsonobject
Array, a group of ordered data lists. Org. JSON. jsonarray
Android contains four JSON-related classes and one exceptions:
Jsonarray
Jsonobject
Jsonstringer
Jsontokener
Jsonexception
Jsonobject:
This is the basic unit related to the json definition in the system. It contains a pair of key/value values. Its response to an external call (External: Applying the value output by the tostring () method) is a standard string (for example, {"JSON": "Hello, world "}, the outmost is enclosed by braces, and the key and value are separated by colons ). The operation format for internal (internal) behaviors is slightly. For example, to initialize a jsonobject instance, reference the internal put () method to add a value: New jsonobject (). put ("JSON", "Hello, world! "), Separate keys and values with commas.
Value types include: Boolean, jsonarray, jsonobject, number, string, or the default value jsonobject. null object.
There are two different value methods:
Get (): used when a specified value exists. Otherwise, an exception is thrown when the key cannot be retrieved.
Opt (): This method is relatively flexible. If the specified value cannot be obtained, a default value is returned and no exception is thrown.
Jsonarray:
It represents a group of ordered values. The format of tostring output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3], you can use the short Code More intuitive understanding of its format ). This class has the same internal query behavior. The get () and OPT () methods can both return the specified value through the index, and the put () method is used to add or replace the value.
The Value Type of this class can also include: Boolean, jsonarray, jsonobject, number, string, or the default value jsonobject. null object.
Jsonstringer:
According to the official explanation, this class can help you quickly and conveniently create jsontext. Its biggest advantage is that it can reduce the number of errors caused by format errors. Program Exception. You can reference this class to automatically create JSON text in strict accordance with the JSON syntax rules (syntaxrules. Each jsonstringer object can only create one JSON text.
Learn more about the following instances:
1. String mystring = new jsonstringer (). Object ()
2. Key ("Ar"). Value ("www.androidres.com !")
3. endobject ()
4. tostring ();
The result is a set of standard format JSON text: {"ar": "www.androidres.com !"}
The. Object () and. endobject () must be used at the same time to add a boundary to the value according to the object standard. Likewise, there are a set of standard methods for arrays to generate the boundary. Array () and. endarray ().
Jsontokener:
This is the class in which the system parses the JSON source string for the jsonobject and jsonarray constructors. It can extract numerical information from the source string.
Jsonexception:
Is the exception information thrown by the json.org class.
A complete application instance is referenced below
(From: androidsnippets.org)
Use jsonobject to store map-type values:
01. Public static jsonobject getjson (MAP map ){
02. iterator iter = map. entryset (). iterator ();
03. jsonobject holder = new jsonobject ();
04.
05. While (ITER. hasnext ()){
06. Map. Entry pairs = (Map. Entry) ITER. Next ();
07. String key = (string) pairs. getkey ();
08. Map M = (MAP) pairs. getvalue ();
09. jsonobject DATA = new jsonobject ();
10.
11. Try {
12. iterator iter2 = M. entryset (). iterator ();
13. While (iter2.hasnext ()){
14. Map. Entry pairs2 = (Map. Entry) iter2.next ();
15. Data. Put (string) pairs2.getkey (), (string) pairs2.getvalue ());
16 .}
17. Holder. Put (Key, data );
18.} catch (jsonexception e ){
19. log. E ("Transforming", "there was an error packaging JSON", e );
20 .}
21 .}
22.
23. Return holder;
24 .}
When Android calls WebService, it often needs to process the JSON format. Currently, there are two methods:
To process:
1 use jsonobject and jsontokener for parsing
2. Use the gson Library
First, let's look at the first method, for example, the following JSON string:
{
"Name": "myname ",
"Message": ["mymessage1", "mymessage2"],
"Place": "myplace ",
"Date": "thisdate"
}
Solution 1:
Public class main extends activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Try {
Textview TV = (textview) findviewbyid (R. Id. textview01 );
String JSON = "{"
+ "\" Name \ ": \" myname \","
+ "\" Message \ ": [\" mymessage1 \ ", \" mymessage2 \ "],"
+ "\" Place \ ": \" myplace \","
+ "\" Date \ ": \" thisdate \""
+ "}";
/* Create a JSON object and parse the required values */
Jsonobject object = (jsonobject) New jsontokener (JSON). nextvalue ();
String name = object. getstring ("name ");
String place = object. getstring ("place ");
String date = object. getstring ("date ");
Jsonarray message = object. getjsonarray ("message ");
TV. settext ("Name:" + name + "\ n ");
TV. append ("place:" + place + "\ n ");
TV. append ("Date:" + date + "\ n ");
For (INT I = 0; I <message. Length (); I ++)
{
TV. append ("message:" + message. getstring (I) + "\ n ");
}
2. Use the gson class library
The gson class library provided by Google is:
The Code is as follows:
Public class json_structure {
Public string name;
Public String place;
Public String date;
Public String [] message;
}
This is actually a pojo class.
Try {
/* Inflate textview from the Layout */
Textview TV = (textview) findviewbyid (R. Id. textview01 );
/* JSON data considered as an example. Generally this data is obtained
From a web service .*/
String JSON = "{"
+ "\" Name \ ": \" myname \","
+ "\" Message \ ": [\" mymessage1 \ ", \" mymessage2 \ "],"
+ "\" Place \ ": \" myplace \","
+ "\" Date \ ": \" thisdate \""
+ "}";
Gson = new gson ();
Json_structure OBJ = gson. fromjson (JSON, json_structure.class );
TV. settext ("name:" + obj. Name + "\ n ");
TV. append ("Place:" + obj. Place + "\ n ");
TV. append ("Date:" + obj. Date + "\ n ");
For (INT I = 0; I <obj. Message. length; I ++)
{
TV. append ("message:" + obj. Message [I] + "\ n ");
}
}
Catch (exception ex) {ex. printstacktrace ();}
}
} Catch (jsonexception e) {e. printstacktrace ();}
Catch (exception ex) {ex. printstacktrace ();}
}
}

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.