Android enables parsing of JSON data and converting data into JSON-formatted strings

Source: Internet
Author: User

Using the Android SDK

Jsonobject and Jsonarray Convert collections or normal data into JSON-formatted strings

Jsonobject and Jsonarray parse JSON-formatted strings as collections or generic data

Package Com.hck.test;import Java.util.arraylist;import java.util.list;import org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Android.app.activity;import Android.os.Bundle;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.textview;import android.widget.Toast; Public classMainactivity extends Activity implements Onclicklistener {PrivateButton button1, Button2, Button3, Button4;//4 x Buttons    PrivateTextView TextView;//show TextView of processing results    PrivateList<userbean> Userbeans;//save a collection of data    PrivateJsonobjectObject;//Jsonobject object, handling an object of one    PrivateJsonobject Object2; PrivateJsonarray Jsonarray;//A Jsonobject object that processes a collection or array    PrivateString jsonstring;//to save a JSON string with a collection    PrivateString jsonString2;//JSON string without a collection@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); Initview (); //Initializing the controlInitdate ();//Initializing DataSetlistener ();//Binding a Supervisor event            }    Private voidInitview () {button1=(Button) Findviewbyid (R.ID.BT1); Button2=(Button) Findviewbyid (R.ID.BT2); Button3=(Button) Findviewbyid (R.ID.BT3); Button4=(Button) Findviewbyid (R.ID.BT4); TextView=(TextView) Findviewbyid (R.id.text); }/** * Initialize 2 user objects*/    Private voidinitdate () {Userbeans=NewArraylist<userbean>(); UserBean UserBean=NewUserBean (); Userbean.setuserid (1); Userbean.setusername ("Hck");        Userbeans.add (UserBean); UserBean userBean2=NewUserBean (); Userbean2.setuserid (2); Userbean2.setusername ("Tadpoles");    Userbeans.add (USERBEAN2); }    Private voidSetlistener () {Button1.setonclicklistener ( This); Button2.setonclicklistener ( This); Button3.setonclicklistener ( This); Button4.setonclicklistener ( This); }    Private voidChangearraydatetojson () {//converts a collection into a JSON-formatted stringjsonarray=NULL; Object=NULL; Jsonarray=NewJsonarray (); Object=NewJsonobject ();  for(inti =0; I < userbeans.size (); i++) {//iterate through the above initialized collection data and add the data to the JsonobjectObject2 =NewJsonobject ();//a user object that uses a Jsonobject object to load            Try{object2.put ("userId", Userbeans.Get(i). GetUserId ());//take the data from the collection, put it inside the Jsonobject Jsonobject object and map, store the data in the form of keys and valuesObject2.put ("UserName", Userbeans.Get(i). GetUserName ()); Jsonarray.put (OBJECT2); //load the Jsonobject object into the Jsonarray array}Catch(jsonexception e) {e.printstacktrace (); }        }                Try {            Object. put ("userdate", Jsonarray);//Add the Jsonarray data to the Jsonobject object (the array is also the object)//Object.put ("Time", "2013-11-14");//data can also be added here, so that the JSON string, which has both a collection and normal data}Catch(jsonexception e) {e.printstacktrace (); } jsonstring=NULL; Jsonstring=Object. toString ();//convert Jsonobject to JSON-formatted stringTextview.settext (jsonstring); LOG.I ("Hck","convert to JSON string:"+jsonstring); }    Private voidChangenotarraydatetojson () {Object=NULL; Object=NewJsonobject (); Try {            Object. put ("userId","1");//Add the data to the Jsonobject object, and "userid" equals the value of the key,1 in the map.             Object. put ("UserName","Hck"); } Catch(jsonexception e) {e.printstacktrace (); } jsonString2=NULL; JsonString2=Object. toString ();//convert Jsonobject to JSON-formatted stringLOG.I ("Hck","convert to JSON string:"+jsonString2);    Textview.settext (JSONSTRING2); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.bt1:changenotarraydatetojson ();//Click the first button to convert the collection to a JSON data format string             Break;  CaseR.id.bt2:changearraydatetojson ();//Click the 2nd button to change the normal data to a JSON data format string             Break;  CaseR.ID.BT3://parse a JSON string without a collection             if(jsonstring2==NULL||"". Equals (JsonString2)) {Toast.maketext (mainactivity). This,"Please click on the 1th button above to change the data into a JSON string", Toast.length_long). Show (); return;            } changeJsonToData2 ();  Break;  CaseR.ID.BT4://parse a JSON string with a collection             if(jsonstring==NULL||"". Equals (jsonstring)) {Toast.maketext (mainactivity). This,"Please first click on the 2nd button to change the data to a JSON string", Toast.length_long). Show (); return;                        } changeJsonToData1 ();  Break; default:             Break; }    }    Private voidchangeJsonToData1 () {StringBuilder StringBuilder=NewStringBuilder ();//used to save the parsed amount of data, shown in TextViewUserBean UserBean; List<UserBean> blist=NewArraylist<userbean>(); Try {            Object=NewJsonobject (jsonstring);//get a Jsonobject object in a JSON-formatted stringjsonarray=Object. Getjsonarray ("userdate");//get a Jsonarray array inside the Jsonobject via key             for(inti =0; I < jsonarray.length (); i++) {//traversing Data                Object=jsonarray.getjsonobject (i);//get a Jsonobject object from Jsonarrayuserbean=NewUserBean (); Userbean.setuserid (Object. GETINT ("userId"));//through key, get the data insideUserbean.setusername (Object. getString ("UserName"));            Blist.add (UserBean); }        } Catch(jsonexception e) {e.printstacktrace (); }         for(inti =0; I < blist.size (); i++) {stringbuilder.append ("User id:"+blist.Get(i). GetUserId ()). Append ("   "). Append ("User name:"+blist.Get(i). GetUserName ()); } textview.settext (Stringbuilder.tostring (). Replace ("NULL","")); }    Private voidChangeJsonToData2 () {Try {            Object=NewJsonobject (JSONSTRING2); String UserName=Object. getString ("UserName"); String useridstring=Object. getString ("userId"); Textview.settext ("User ID"+useridstring+"User name:"+userName); } Catch(jsonexception e) {e.printstacktrace (); }    }}

Android enables parsing of JSON data and converting data into JSON-formatted strings

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.