What is JSON
1. JSON: JavaScript Object Notation
2. JSON data is a collection of key-value pairs.
3. JSON has been accepted by most developers and is widely used in network data transmission.
4. JSON is easier to parse than XML
JSON and XML
1. The data readability of JSON and XML is basically the same.
2. JSON and XML have rich parsing methods.
3. JSON is small in size than XML
4. easier interaction between JSON and JavaScript
5. Relatively poor description of data in JSON
Jsonreader is supported from Android 3.0
Therefore, to use Google's gson API, You need to download the jar package and manually add it.
Jsondata is the JSON data to be parsed:
[{"Name": "zhangsan", "Age": 20 },{ "name": "Lisi", "Age": 30}]
Try {
Jsonreaderreader = new jsonreader (New stringreader (jsondata ));
Reader. beginarray ();
While (reader. hasnext ()){
Reader. beginobject ();
While (reader. hasnext ()){
Stringtagname = reader. nextname ();
If (tagname. Equals ("name ")){
System. Out. prinltn ("name --->" + reader. nextstring ());
}
Elseif (tagname. Equals ("Age ")){
System. Out. println ("age --->" + reader. nextstring ());
}
}
Reader. endobject ();
}
Reader. endarray ();
}
Catch (exception e ){
E. printstacktrace ();
}
Jsondata is {"Name": "Michael", "Age": 30}
Public class User{
PrivateString name;
Private intAge;
PublicString getname (){
ReturnName;
}
Public voidSetname (string name ){
This. Name = Name;
}
Public intGetage (){
ReturnAge;
}
Public voidSetage (IntAge ){
This. Age = age;
}
}
GsonGson =New Gson();//GsonObjects provided by the class library
User user =Gson. Fromjson (Jsondata, User.Class);// Convert a JSON object to a user object
Jsondata is [{"Name": "Michael", "Age": 30 },{ "name": "Mary", "Age": 20}]
TypeListtype =NewTypetoken <shortlist <user> () {}. GetType ();
GsonGson =New Gson();
Shortlist<User> Users =Gson. Fromjson (Jsondata,
Listtype); // Convert multiple data into a user Array
For(IteratorIterator =Users. Iterator (); iterator. hasnext ();){
UserUser = (User)Iterator. Next ();
}