Json interaction between android client and webservice

Source: Internet
Author: User

 

Data transmission volume
For equivalent data, Json requires less data to be transmitted and more xml data. This is critical for machines that focus on data volumes.

Scalability,
Although xml has a scalable name, xml is not scalable, and json is not scalable.

Encoding difficulty
Xml cross-platform access is more prone to problems. Although there are many tools, it is not very easy to easily call cross-platform access. json can be written manually and the encoding is much simpler.

Decoding difficulty
I think json is a huge problem. It is very troublesome to process special characters. Xml, such as soap, usually does not have this problem. You only need to consider how to encode it. It is rare that it cannot be parsed due to special characters.

More mainstream
JSON. Although decoding may sometimes cause problems, it looks more concise and easy to debug.

In addition, we recommend a google protobuf, which is the king of efficiency. Many google services use this, including google market.

Json is lightweight, easy to use, and easy to convert to Java objects; and the client script js is easy to get, Android already supports the standard JSON library.
Xml is generally used when the data volume is large or the data structure is complex.

Android has a very wide application in Android development: the Android project obtains the resources of another web project or the returned data.
 
This document obtains the JSON data returned by the web project. Android applications have better performance in JSON parsing than XML, but many projects still use XML.
 
Json:

In the early 21st century, Douglas Crockford looked for a simple data exchange format that could exchange data between servers. At that time, the Common Data Exchange Language was XML, but Douglas Crockford thought that XML generation and parsing were too troublesome, so he proposed a simplified format, namely Json.

The Json specification is very simple. It can be clearly stated in just a few hundred words on a page, and Douglas Crockford claims that this specification will never need to be upgraded, because it is stipulated in this provision.

1) Separate the parallel data with commas.

2) The ing is represented by a colon.

3) The set (array) of the parallel data is represented by square brackets.

4) The ing set (object) is represented by braces.

The above four rules are all in Json format.

For example, the following sentence:

"Beijing has an area of 16800 square kilometers and a resident population of 16 million people. Shanghai has an area of 6400 square kilometers and a resident population of 18 million. "

The json format is as follows:

[
{"City": "Beijing", "area": 16800, "Population": 1600 },
{"City": "Shanghai", "area": 6400, "Population": 1800}
]

If you know the data structure in advance, the preceding statement can be further simplified:

[
["Beijing", 16800,1600],
["Shanghai", 6400,1800]
]

 


Java definition example:


Private String jsonData1 = "[{\" name \ ": \" renhaili \ ", \" age \ ": 20 },{ \" name \": \ "zhouxiaodong \", \ "age \": 21}] ";
Private String jsonData2 = "{\" name \ ": \" xiong \ ", \" age \ ": 18 }";


Json is easy to learn and use. Therefore, in just a few years, it has replaced xml and become the most popular data exchange format on the Internet.

 

 


The first method is convenient and simple:

 


Recently, I used Android to call the Web service and started to prepare WebService for calling. After I wrote it in jws WebService mode, I found that many problems were solved during Android calling, later, we found that there was a better way to use HttpPost to interact with the background.

The following describes the related JSON operations:

 

I have to say that the JSON format is indeed very good, fast and simplified a lot of operations.
In Android, the Android SDK has encapsulated the entire JSON-related operation for us, which is very convenient to use.

The following is the implementation process of a standard JSON request:

HttpPost request = new HttpPost (url );
// Encapsulate a JSON object first
JSONObject param = new JSONObject ();
Param. put ("name", "rarnu ");
Param. put ("password", "123456 ");
// Bind to the request Entry
StringEntity se = new StringEntity (param. toString ());
Request. setEntity (se );
// Send the request
HttpResponse httpResponse = new defaulthttpclient(.exe cute (request );
// Obtain the response string, which is also the data saved in JSON format
String retSrc = EntityUtils. toString (httpResponse. getEntity ());
// Generate a JSON object
JSONObject result = new JSONObject (retSrc );
String token = result. get ("token ");

 

 

 

The second traditional one:

 

 


Package com. practice. json;

Import org. json. JSONArray;
Import org. json. JSONException;
Import org. json. JSONObject;

Import android. app. Activity;
Import android. OS. Bundle;
Import android. util. Log;

Public class JsonDemo extends Activity {
/*
* JSON parsing example. str stores the JSON code, and the parsed data is output in LogCat.
*/

String TAG = "Json message ";

@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
DetectJSON ();
}

Private void detectJSON (){
String str = "{" +

"\" Date \ ": \" 2011-06-06 \ "," +

// Like is JSONObject
"\" Like \ ": {" +
"\" Name \ ": \" Garnett \ "," +
"\" Height \ ": \" 11cm \ "," +
"\" Age \ ": 35" +
"}," +

// LikeList is a JSONObject
"\" LikeList \ ":" +
"{\" List \ ":" +
"[" +
// JSONObject
"{" +
"\" Name \ ": \" Rose \ "," +
"\" Height \ ": \" 190cm \ "," +
"\" Age \ ": 23" +
"}," +
// JSONObject
"{" +
"\" Name \ ": \" Kobe \ "," +
"\" Height \ ": \" 198cm \ "," +
"\" Age \ ": 33" +
"}" +
"]" +
"}" +
"}";

Try {
JSONObject dataJson = new JSONObject (str );
Log. d (TAG, dataJson. getString ("date "));

JSONObject nbaJson = dataJson. getJSONObject ("Like ");

Log. d (TAG, nbaJson. getString ("Name "));
Log. d (TAG, nbaJson. getString ("Height "));
Log. d (TAG, nbaJson. get ("Age"). toString ());

JSONObject listJson = dataJson. getJSONObject ("LikeList ");
JSONArray arrayJson = listJson. getJSONArray ("List ");

For (int I = 0; I <arrayJson. length (); I ++ ){

JSONObject tempJson = arrayJson. optJSONObject (I );

Log. d (TAG, tempJson. getString ("Name "));
Log. d (TAG, tempJson. getString ("Height "));
Log. d (TAG, tempJson. getString ("Age"). toString ());
}


} Catch (JSONException e ){
System. out. println ("Something wrong ...");
E. printStackTrace ();
}
}
}


 

Related Article

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.