JSON data parsing for Android development

Source: Internet
Author: User

JSON data parsing for Android development This blog is mainly about the use of Google's Lib library Gson parsing JSON data, because Android's own JSON data parser can only be used in Android version 3.0 or more, if you need to use Gson, We need to add the Gson Lib library file to the project and add path. The detailed code is as follows:
Mainactivyty.java:
Package Com.example.analysisjson;

Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;


public class Mainactivity extends Activity {


Private Button MyButton = null;
Private String Jsondata = "[{\" name\ ": \" zhangsan\ ", \" age\ ": 21},{\" name\ ": \" lisi\ ", \" age\ ": 33}]";
Private String Jsonojectdata = "{\" name\ ": \" zhangsan\ ", \" age\ ": 21}";
Private String Jsonojectsdata = "[{\" name\ ": \" zhangsan\ ", \" age\ ": 21},{\" name\ ": \" lisi\ ", \" age\ ": 33}]";

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
MyButton = (Button) Findviewbyid (R.id.mybutton);
Mybutton.setonclicklistener (New Setbuttonlistener ());
}

Class Setbuttonlistener implements onclicklistener{

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Jsonutils jsonutils = new Jsonutils ();
Parsing JSON arrays
Jsonutils.parsearraydata (Jsondata);
Parsing a single JSON object
Jsonutils.parseobjectdata (Jsonojectdata);
Parsing multiple JSON objects
Jsonutils.parseobjectsdata (Jsonojectsdata);
}

}


@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}


}


Jsonutils.java:

Package Com.example.analysisjson;


Import java.io.IOException;
Import Java.io.StringReader;
Import Java.lang.reflect.Type;
Import Java.util.Iterator;
Import java.util.LinkedList;


Import Android. R.integer;




Import Com.google.gson.Gson;
Import Com.google.gson.reflect.TypeToken;
Import Com.google.gson.stream.JsonReader;


/*
* The Jsonreader for Android should only support more than 3.0 versions.
* Here is mainly the use of Google's Gson parser, parsing json, no version of the restrictions
* You need to add Gson Libs to your project
* */


public class Jsonutils {

/*
* Example: "[{\" name\ ": \" zhangsan\ ", \" age\ ": 21},{\" name\ ": \" lisi\ ", \" age\ ": 33}]"
* The steps for JSON array parsing are as follows:
* 1. Start parsing arrays
* 2. Start parsing objects
* 3, analytic key value pair
* 4, the resolution of the key value of the end
* 5. End of parsing object
* 6, parsing the end of the array
* */
public void Parsearraydata (String jsondata) {

try {
Jsonreader Jsonreader = new Jsonreader (new StringReader (Jsondata));
Jsonreader.beginarray ();
while (Jsonreader.hasnext ()) {
Jsonreader.beginobject ();
while (Jsonreader.hasnext ()) {
String tagName = Jsonreader.nextname ();
if (tagname.equals ("name")) {
System.out.print ("name-to" + jsonreader.nextstring ());
}else if (tagname.equals ("Age")) {
System.out.println ("; age--" + jsonreader.nextint ());
}
}
Jsonreader.endobject ();
}
Jsonreader.endarray ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

}


/*
* Example: "{\" name\ ": \" zhangsan\ ", \" age\ ": 21}"
* Use Google Gson to parse a single JSON object
*
* */
public void Parseobjectdata (String jsondata) {
try{
Gson Gson = new Gson ();
User user = Gson.fromjson (jsondata, User.class);
System.out.print ("name-to" + user.getname ());
System.out.println ("; age-->" + user.getage ());
}catch (Exception e) {
E.printstacktrace ();
}
}


/*
* Example: "{\" name\ ": \" zhangsan\ ", \" age\ ": 21}"
* Use Google Gson to parse multiple JSON objects
*
* */
public void Parseobjectsdata (String jsondata) {
try{
Type type = (type) new Typetoken<linkedlist<user>> () {}.gettype ();
Gson Gson = new Gson ();

linkedlist<user> users = Gson.fromjson (jsondata, type);

for (iterator<user> Iterator = Users.iterator (); Iterator.hasnext ();) {
User user = Iterator.next ();
System.out.print ("name-to" + user.getname ());
System.out.println ("; age-->" + user.getage ());
}

}catch (Exception e) {
E.printstacktrace ();
}
}



}

Main layout file Main.java:
<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:paddingbottom= "@dimen/activity_vertical_margin"
android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin"
android:paddingtop= "@dimen/activity_vertical_margin"
Tools:context= ". Mainactivity ">


<textview
Android:id= "@+id/mytext"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "@string/hello_world"/>

<button
Android:id= "@+id/mybutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:layout_below= "@id/mytext"
android:text= "Start parsing json"/>


</RelativeLayout>


When you click the Parse JSON button, the parsed data is output in the Logcat .

JSON data parsing for Android development

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.