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 ();}
}
}