Work bit-by-bit Json Parsing

Source: Internet
Author: User

During Android development, data transmission is inevitable. Generally, there are two ways to organize data: xml format and json format. Both of them are very convenient to parse, and there are also a lot of parsing tools, so we will not compare them here.
The following is a more practical analysis of Json Format Parsing:
1) parse data in Json format
2) parse a single object
3) set of parsed objects
 
A major premise-What is Json?
1. If you do not know what Json is, scan the blind
1) JSON: JavaScript Object Notation
2) JSON data is a collection of key-value pairs.
3) Official Website: www.json.org. You will understand everything.
 
2. Json vs xml
1) the readability of JSON and XML is basically the same.
2) JSON and XML have a wide range of parsing Methods
3) JSON is smaller than XML.
4) The interaction between JSON and JavaScript is more convenient.
5) The data description in JSON is relatively poor.
 
Ii. JSON parsing tools in Android
1. Starting from API level 11 (Android3.0), there are two help classes: JsonReader and JsonWriter In the android. util package for us to parse and use json.
 
2. The best practice for systems below Android3.0 is to use Google's gson class library for parsing. In fact, this is also the practice after 3.0, but it is integrated,
: Http://code.google.com/p/google-gson/downloads/list
 
3. Import the downloaded jar file to the project. I believe this will be done by everyone. The following example uses gson for parsing.
 
Three JSON practices
1. parse data in json format
For example, a User object has two attributes: name and age. Of course, more attributes may exist in actual conditions,
In json format: {name: "Ian", age: "20"}, I believe you know.
1) custom JSON help class -- JsonUtils
Java code
Public class JsonUtils {

Public void parseJson (String jsonData ){

Try {
JsonReader reader = new JsonReader (new StringReader (jsonData ));
Reader. beginArray ();
While (reader. hasNext ()){
Reader. beginObject ();
While (reader. hasNext ()){
String tagName = reader. nextName ();
If (tagName. equals ("name ")){
System. out. println ("name --->" + reader. nextString ());
} Else if (tagName. equals ("age ")){
System. out. println ("age --->" + reader. nextString ());
}
}
Reader. endObject ();
}
Reader. endArray ();
} Catch (IOException e ){
E. printStackTrace ();
}

}
}
 
 
2) Activity code
 
Java code
Public class MainActivity extends Activity {
Private Button btnStart;
Private String jsonDataUser = "{\" name \ ": \" Ian \ ", \" age \ ": 20 }";
 
 
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

BtnStart = (Button) findViewById (R. id. btnStart );
BtnStart. setOnClickListener (new BtnStartSetOnClickListener ());


}

Private class BtnStartSetOnClickListener implements OnClickListener {
@ Override
Public void onClick (View v ){
JsonUtils jsonUtils = new JsonUtils ();
JsonUtils. parseJson (jsonData );
}
}
}
Just a few lines of code can be seen on the Console to parse the output information, isn't it easy?
 
 
2. parse object
1) The above parses the string format. What if we define a User object?
 
Java code
Public class User {
Private String name;
Private int age;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
}
 
2) Resolution Method
 
Java code
Public void parseUserFromJson (String jsonData ){

Gson gson = new Gson ();
User user = gson. fromJson (jsonData, User. class );
System. out. println ("name ---------->" + user. getName ());
System. out. println ("age ---------->" + user. getAge ());

}
 
Is it simpler?
 
3. parsing set
1) if it is not a single User but an ArrayList <User>, how should we resolve it? This is too common.
To solve this problem, you must first understand how to express the set in json. In short, "{}" represents an object, and "[]" represents a set, the set can contain multiple objects, indicating [{},{},{}]. OK, so let's look at the actual code,
Json data:
 
Java code
Private String jsonDataUsers = "[{\" name \ ": \" Jack \ ", \" age \ ": 20 },{ \" name \": \ "Tom \", \ "age \": 22 },{ \ "name \": \ "Ian \", \ "age \": 20}] ";
Parsing Code:
 
Java code
Public void parseUserFromJson (String jsonData ){
 
Type typeList = new TypeToken <ArrayList <User> () {}. getType ();
Gson gson = new Gson ();
Using list <User> users = gson. fromJson (jsonData, typeList );
For (Iterator <User> iterator = users. iterator (); iterator. hasNext ();){
User user = iterator. next ();
System. out. println ("name ---------->" + user. getName ());
System. out. println ("age ---------->" + user. getAge ());
}
}
 
We can see that there is only one more line "Type typeList = new TypeToken <ArrayList <User> (){}. getType (); ", You can parse the List and iterate the List to get the entire data.
It's really convenient. What are you waiting for? Please try it!

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.