This article is followed by the Android access to WCF (next)-Client development deserializes the JSON data obtained by the server through the GSON class library and displays it through the UI.
How to deserialize JSON data with GSON on Android platform, refer to this article http://benjii.me/2010/04/deserializing-json-in-android-using-gson/
1. Create our packaged Http request class file websiteetapi. java
Package com. demo; </p> <p> import java. io. IOException; <br/> import java. io. inputStreamReader; <br/> import java. io. unsupportedEncodingException; </p> <p> import org. apache. http. httpEntity; <br/> import org. apache. http. httpResponse; <br/> import org. apache. http. client. methods. httpGet; <br/> import org. apache. http. impl. client. defaultHttpClient; <br/> import org. apache. http. params. basicHttpParams; <br/> import org. apache. http. protocol. HTTP; </p> <p> import android. util. log; </p> <p> public class websiteetapi {</p> <p> private static final String TAG = "websiteetapi "; <br/> private static final String USER_AGENT = "Mozilla/4.5"; </p> <p> protected String getRequest (String url) throws Exception {<br/> return getRequest (url, new DefaultHttpClient (new BasicHttpParams ())); <br/>}</p> <p> protected String getRequest (String url, DefaultHttpClient client) <br/> throws Exception {<br/> String result = null; <br/> int statusCode = 0; <br/> HttpGet getMethod = new HttpGet (url); <br/> Log. d (TAG, "do the getRequest, url =" + url + ""); <br/> try {<br/> getMethod. setHeader ("User-Agent", USER_AGENT); <br/> // HttpParams params = new HttpParams (); </p> <p> // Add User Password Verification Information <br/> // client. getCredentialsProvider (). setCredentials (<br/> // new AuthScope (null,-1), <br/> // new UsernamePasswordCredentials (mUsername, mPassword )); </p> <p> HttpResponse httpResponse = client.exe cute (getMethod); <br/> // normal statusCode = 200 <br/> statusCode = httpResponse. getStatusLine (). getStatusCode (); <br/> Log. d (TAG, "statuscode =" + statusCode); <br/> // process returned httpResponse Information <br/> result = retrieveInputStream (httpResponse. getEntity (); <br/>}catch (Exception e) {<br/> Log. e (TAG, e. getMessage (); <br/> throw new Exception (e); <br/>}finally {<br/> getMethod. abort (); <br/>}< br/> return result; <br/>}</p> <p>/** <br/> * process httpResponse information, return String <br/> * @ param httpEntity <br/> * @ return String <br/> */<br/> protected String retrieveInputStream (HttpEntity httpEntity) {<br/> int length = (int) httpEntity. getContentLength (); <br/> if (length <0) <br/> length = 10000; <br/> StringBuffer stringBuffer = new StringBuffer (length ); <br/> try {<br/> InputStreamReader inputStreamReader = new InputStreamReader (<br/> httpEntity. getContent (), HTTP. UTF_8); <br/> char buffer [] = new char [length]; <br/> int count; <br/> while (count = inputStreamReader. read (buffer, 0, length-1)> 0) {<br/> stringBuffer. append (buffer, 0, count); <br/>}< br/>} catch (UnsupportedEncodingException e) {<br/> Log. e (TAG, e. getMessage (); <br/>} catch (IllegalStateException e) {<br/> Log. e (TAG, e. getMessage (); <br/>}catch (IOException e) {<br/> Log. e (TAG, e. getMessage (); <br/>}< br/> return stringBuffer. toString (); <br/>}< br/>}2. Establish JsonDataGetApi. java Package com. demo; </p> <p> import org. json. JSONArray; <br/> import org. json. JSONException; <br/> import org. json. JSONObject; </p> <p> public class JsonDataGetApi extends webappsetapi {<br/> private static final String BASE_URL = "http: // 10.0.2.2: 82/AccountService /"; <br/> private static final String EXTENSION = "Json/"; </p> <p> public JSONObject getObject (String sbj) throws JSONException, exception {<br/> return new JSONObject (getRequest (BASE_URL + EXTENSION + sbj); <br/>}</p> <p> public JSONArray getArray (String sbj) throws JSONException, Exception {<br/> return new JSONArray (getRequest (BASE_URL + EXTENSION + sbj); <br/>}< br/>}
3. Create an Account model for Android client Account. java
Import java. util. date; </p> <p> public class Account {</p> <p> public String Name; </p> <p> public int Age; </p> <p> public String Address; </p> <p> public Date Birthday; <br/>}4. Calling the method just now in our main Activity, in this step we need to introduce Google's gson library gson-1.6.jar to our project ()Package com. demo; </p> <p> import java. util. date; </p> <p> import org. json. JSONArray; <br/> import org. json. JSONObject; </p> <p> import com. google. gson. gson; <br/> import com. google. gson. gsonBuilder; </p> <p> import android. app. activity; <br/> import android. OS. bundle; <br/> import android. util. log; <br/> import android. widget. textView; <br/> import android. widget. toast; </p> <p> public class WebData extends Activity {<br/>/** Called when the activity is first created. */<br/> @ Override <br/> public void onCreate (Bundle savedInstanceState) {<br/> super. onCreate (savedInstanceState); <br/> setContentView (R. layout. main); <br/> getJsonData (); <br/>}</p> <p> public void getJsonData () {<br/> JsonDataGetApi api = new JsonDataGetApi (); <br/> JSONArray jArr; <br/> JSONObject jobj; <br/> try {<br/> // call the GetAccountData method <br/> jArr = api. getArray ("GetAccountData"); <br/> // retrieve the first data from the returned Account Array <br/> jobj = jArr. getJSONObject (0); </p> <p> GsonBuilder gsonb = new GsonBuilder (); <br/> // The Date expression in Json cannot be directly converted to our Date type. Therefore, you must register a single Date deserialization class. <br/> // DateDeserializer ds = new DateDeserializer (); <br/> // specify the Date type deserialization method for the GsonBuilder method <br/> // gsonb. registerTypeAdapter (Date. class, ds); </p> <p> Gson gson = gsonb. create (); </p> <p> Account account = gson. fromJson (jobj. toString (), Account. class); </p> <p> Log. d ("LOG_CAT", jobj. toString (); <br/> (TextView) findViewById (R. id. name )). setText (account. name); <br/> (TextView) findViewById (R. id. age )). setText (account. age); <br/> (TextView) findViewById (R. id. birthday )). setText (account. birthday <br/>. toGMTString (); <br/> (TextView) findViewById (R. id. address )). setText (account. address); </p> <p >}catch (Exception e) {<br/> Toast. makeText (getApplicationContext (), e. getMessage (), <br/> Toast. LENGTH_LONG ). show (); <br/> e. printStackTrace (); <br/> TextView movie_Address = (TextView) findViewById (R. id. address); <br/> movie_Address.setText (e. getMessage (); <br/>}< br/>5. We started to build the UI.
Open main. xml in layout
<? Xml version = "1.0" encoding = "UTF-8"?> <Br/> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" <br/> android: orientation = "vertical" android: layout_width = "fill_parent" <br/> android: layout_height = "fill_parent"> <br/> <TextView android: id = "@ + id/Name" android: layout_width = "fill_parent" <br/> android: layout_height = "wrap_content"/> <br/> <TextView android: id = "@ + id/Age" android: layout_width = "fill_parent" <br/> android: layout_height = "wrap_content"/> <br/> <TextView android: id = "@ + id/Birthday" android: layout_width = "fill_parent" <br/> android: layout_height = "wrap_content"/> <br/> <TextView android: id = "@ + id/Address" android: layout_width = "fill_parent" <br/> android: layout_height = "wrap_content"/> <br/> </LinearLayout> </p> <p>After the RunConfiguration is configured, run the program and check the Log to find the following errors,
This means that access is forbidden, that is, unauthorized access. This means that our service is not unauthorized, because Andriod has a good security mechanism, we must be authorized to access the network;
Open AndroidManifest. xml in the res directory, and note that the font is to add Internet Access Authorization to our program.
<? Xml version = "1.0" encoding = "UTF-8"?> <Br/> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" <br/> package = "com. demo "<br/> android: versionCode =" 1 "<br/> android: versionName =" 1.0 "> </p> <uses-permission android: name = "android. permission. INTERNET "> </uses-permission> </p> <application android: icon =" @ drawable/icon "android: label = "@ string/app_name"> <br/> <activity android: name = ". webData "<br/> android: label =" @ string/app_name "> <br/> <intent-filter> <br/> <action android: name =" android. intent. action. MAIN "/> <br/> <category android: name =" android. intent. category. LAUNCHER "/> <br/> </intent-filter> <br/> </activity> </p> </application> <br/> </manifest>When you run the program again, the following information is displayed:
From the statuscode = 200 in, it indicates that our request has been successful and the problem occurs in the process of Json Parse (Json data conversion/deserialization/formatting, now let's take out the data from the server and enter our service address: http: // localhost: 82/AccountService/Json/GetAccountData in the browser.
[ { "Address": "YouYi East Road", "Age": 56, "Birthday": "/Date(1298605481453+0800)/", "Name": "Bill Gates" }, { "Address": "YouYi West Road", "Age": 57, "Birthday": "/Date(1298605481453+0800)/", "Name": "Steve Paul Jobs" }, { "Address": "YouYi North Road", "Age": 65, "Birthday": "/Date(1298605481453+0800)/", "Name": "John D. Rockefeller" }]
We found that the Birthday result is not the yyyy-mm-dd HH: mm: ss type we imagined. For the reason, refer to the MSDN Article JavaScript and. introduction to JavaScript Object Notation (JSON) in. NET
Now let's specify the Date serialization Method for our GsonBuilder, first add a Date deserialization class DateDeserializer. java
Package com. demo; </p> <p> import java. lang. reflect. type; <br/> import java. util. date; <br/> import java. util. regex. matcher; <br/> import java. util. regex. pattern; </p> <p> import com. google. gson. jsonDeserializationContext; <br/> import com. google. gson. jsonDeserializer; <br/> import com. google. gson. jsonElement; <br/> import com. google. gson. jsonParseException; </p> <p> public class DateDeserializer implements JsonD Eserializer <Date >{< br/> public Date deserialize (JsonElement json, Type typeOfT, <br/> JsonDeserializationContext context) throws JsonParseException {<br/> String JSONDateToMilliseconds = "\\/ (Date \\((. *?) (\ + .*)? \) \/"; <Br/> Pattern pattern = Pattern. compile (JSONDateToMilliseconds); <br/> Matcher matcher = pattern. matcher (json. getAsJsonPrimitive () <br/>. getAsString (); <br/> String result = matcher. replaceAll ("$2"); <br/> return new Date (new Long (result); <br/>}< br/>}Next, modify the GetDate method in the Activity class as follows. Note the bold part.Public void getJsonData () {<br/> JsonDataGetApi api = new JsonDataGetApi (); <br/> JSONArray jArr; <br/> JSONObject jobj; <br/> try {<br/> // call the GetAccountData method <br/> jArr = api. getArray ("GetAccountData"); <br/> // retrieve the first data from the returned Account Array <br/> jobj = jArr. getJSONObject (0); </p> <p> GsonBuilder gsonb = new GsonBuilder (); <br/> // The Date expression in Json cannot be directly converted to our Date type. Therefore, you must register a single Date deserialization class. <br/> DateDeserializer ds = new DateDeserializer (); <br/> // specify the Date type deserialization method for the GsonBuilder method <br/> gsonb. registerTypeAdapter (Date. class, ds); </p> <p> Gson gson = gsonb. create (); </p> <p> Account account = gson. fromJson (jobj. toString (), Account. class); </p> <p> Log. d ("LOG_CAT", jobj. toString (); <br/> (TextView) findViewById (R. id. name )). setText (account. name); <br/> (TextView) findViewById (R. id. age )). setText (String. valueOf (account. age); <br/> (TextView) findViewById (R. id. birthday )). setText (account. birthday <br/>. toGMTString (); <br/> (TextView) findViewById (R. id. address )). setText (account. address); </p> <p >}catch (Exception e) {<br/> Toast. makeText (getApplicationContext (), e. getMessage (), <br/> Toast. LENGTH_LONG ). show (); <br/> e. printStackTrace (); <br/>}< br/>Now run the program:
Execution successful.
Sample download