Android gets JSON parsing from server to display on client

Source: Internet
Author: User

Android getting JSON parsing from the server is displayed on the client

Baidu Experience: jingyan.baidu.com

First of all, the most basic characteristics of JSON data, JSON data is a series of key-value pairs of the collection, and XML data, the size of the JSON data is smaller, high transmission efficiency, easy to parse, but the readability is not high;

Because this time to get the JSON data from the server side, and after parsing the parsed data displayed in the Android client, first deploy the server-side code (directly using Jsp/servlet):

The JSON data is constructed as follows:

[{"Name": "Zhang San", "Address": "Beijing", "Age": 20},{"name": "John Doe", "Address": "Shanghai", "Age": 30},{"name": "Harry", "Address": "Shenzhen", "Age" : 35}]

[One] server side (Person.java omitted):

①: Data Construction Jsonservice.java

public class Jsonservice {

public static list<person> Getlistperson () {

list<person> mlists = new arraylist<person> ();

Mlists.add (New person ("Zhang San", "Beijing", 20));

Mlists.add (New person ("John Doe", "Shanghai", 30));

Mlists.add (New person ("Harry", "Shenzhen", 35));

return mlists;

}

②:servlet code (including the construction of JSON data, no JSON data conversion method is used) Jsonservlet.java

public void doget (HttpServletRequest request, httpservletresponse response)

Throws Servletexception, IOException {

Response.setcontenttype ("text/html");

Response.setcharacterencoding ("UTF-8");

PrintWriter out = Response.getwriter ();

list<person> persons = Jsonservice.getlistperson ();

StringBuffer sb = new StringBuffer ();

Sb.append (' [');

for (person Person:persons) {

Sb.append (' {'). Append ("\" name\ ":"). Append ("\" "+person.getname () +" \ ""). Append (","); Sb.append ("\" address\ ":"). Append ("\" "+person.getaddress () +" \ ""). Append (",");

Sb.append ("\" age\ ":"). Append (Person.getage ());

Sb.append ('} '). Append (",");

}

Sb.deletecharat (Sb.length ()-1);

Sb.append ('] ');

Out.write (New String (SB));

Out.flush ();

Out.close ();

}

③: Deployment to tomact Browser input Http://localhost/JsonWeb/JsonServlet Direct access results are as follows:

[{"Name": "Zhang San", "Address": "Beijing", "Age": 20},{"name": "John Doe", "Address": "Shanghai", "Age": 30},{"name": "Harry", "Address": "Shenzhen", "Age" : 35}]

At this point the server-side code is completed, the following client code writing; (ii) The client (person class, and the layout file that presents the data because it is simply omitted) ①: Gets the server-side JSON data and resolves the tool class Jsonparse.java necessary to import the package omitted

public class Jsonparse {

/**

* Parse JSON data

*

* @param URLPath

* @return Mlists

* @throws Exception

*/

public static list<person> Getlistperson (String urlpath) throws Exception {

list<person> mlists = new arraylist<person> ();

byte[] data = Readparse (URLPath);

Jsonarray array = new Jsonarray (new String (data));

for (int i = 0; i < array.length (); i++) {

Jsonobject item = array.getjsonobject (i);

String name = item.getstring ("name");

String address = item.getstring ("Address");

int age = Item.getint ("Age");

Mlists.add (new person (name, address, age));

}

return mlists;

}

/**

* Gets the byte array from the specified URL

*

* @param URLPath

* @return byte array

* @throws Exception

*/

public static byte[] Readparse (String urlpath) throws Exception {

Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();

byte[] data = new byte[1024];

int len = 0;

URL url = new URL (urlpath);

HttpURLConnection conn = (httpurlconnection) url.openconnection ();

InputStream instream = Conn.getinputstream ();

while (len = instream.read (data))! =-1) {

Outstream.write (data, 0, Len);

}

Instream.close ();

return Outstream.tobytearray ();

}

}

②: Main Activity class

public class Mainactivity extends Activity {

Private Button Mbutton;

Private ListView Mlistview;

Use IP cannot use localhost or 127.0.0.1, because the Android emulator is bound to this IP by default, the LAN IP should be accessed here

private static final String URLPath = "Http://10.16.31.207/JsonWeb/JsonServlet";

private static final String TAG = "mainactivity";

private list<person> persons;

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

Mbutton = (Button) Findviewbyid (R.id.button1);

Mlistview = (ListView) Findviewbyid (R.ID.LISTVIEW1);

Mbutton.setonclicklistener (New Myonclicklistener ());

}

Private class Myonclicklistener implements Onclicklistener {

@Override

public void OnClick (View v) {

try {

Get the data after the JSON parsing succeeds

Persons = Jsonparse.getlistperson (URLPath);

list

for (int i = 0; i < persons.size (); i++) {

hashmap<string, object> map = new hashmap<string, object> ();

Map.put ("Name", Persons.get (i). GetName ());

Map.put ("Address", Persons.get (i). GetAddress ());

Map.put ("Age", Persons.get (i). Getage ());

Data.add (map);

}

Initialize the adapter, and bind the data

Simpleadapter _adapter = new Simpleadapter (Mainactivity.this,

Data, R.layout.listview_item, new string[] {"Name",

"Address", "age"}, new int[] {r.id.textview1,

R.id.textview2, r.id.textview3});

Mlistview.setadapter (_adapter);

} catch (Exception e) {

Toast.maketext (Mainactivity.this, "Parse Failed", "N"). Show ();

LOG.I (TAG, e.tostring ());

}

}

}

At this point the server side and the client code are introduced, running Android app results:

Android gets JSON parsing from server to display on client

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.