Androidannotation使用之@Rest與server互動的JSON資料轉換(二)

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   io   os   使用   ar   

開篇

之前的一篇部落格:Androidannotation使用之@Rest擷取資源及使用者登入驗證(一):http://blog.csdn.net/nupt123456789/article/details/24384713 主要寫了Rest在使用者登入的時候,須要JSESSION欄位的問題。本部落客要寫JSON格式的轉換。

@Rest的參考文檔:

https://github.com/excilys/androidannotations/wiki/Rest-API#rest

簡單介紹:

從上一篇部落格中,我們能夠看出,我們直接再瀏覽器中請求http://192.168.0.101:8080/cbvr/getUserInfoList.action 的時候,返回的字串事實上是JSON格式。我們上一篇部落格,就是把它直接當String進行處理了,沒有出現什麼問題。當然,我們接下來,能夠使用GSON對String進行解析,這沒有什麼問題。然而,我們通常想,我們換一個轉換器不即可了嗎?代碼例如以下:

/* * $filename: UserService.java,v $ * $Date: 2014-4-20  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testaa;import org.androidannotations.annotations.rest.Accept;import org.androidannotations.annotations.rest.Post;import org.androidannotations.annotations.rest.Rest;import org.androidannotations.api.rest.MediaType;import org.androidannotations.api.rest.RestClientErrorHandling;import org.springframework.http.ResponseEntity;import org.springframework.http.converter.json.GsonHttpMessageConverter;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-4-20  Nanjing,njupt,China */@Rest(rootUrl = "http://192.168.0.101:8080/cbvr", converters = {GsonHttpMessageConverter.class})public interface UserService extends RestClientErrorHandling{@Post("/getUserInfoList.action")@Accept(MediaType.APPLICATION_JSON)ResponseEntity<DataGrid> getUserInfoList();}

這樣,我們就使用了Gson的訊息轉換器,當然,須要匯入GSON相關的包。可是執行程式的時候,發現報錯例如以下:

05-02 16:58:32.644: W/System.err(7454): org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.example.testaa.DataGrid] and content type [text/html;charset=UTF-8]

說什麼沒有合適的HttpMessageConverter,我以為是android端的問題,就換了好幾個轉換器,結果依舊報錯。然後,才發現,原來不是android端的問題,是服務端。服務端每次輸出json字串時,都設定了例如以下屬性:

response.setContentType("text/html;charset=UTF-8");

原來是這個原因,於是,將服務端的改動為例如以下:

response.setContentType("application/json;charset=utf-8");

然後,再次執行,OK了,大功告成!這樣,我們就能夠直接獲得到轉換為JSON格式之後的對象了。為了添加程式的健壯性,為其加入了ErrorHandler處理。餘下代碼例如以下:

package com.example.testaa;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *GitHub   https://github.com/nuptboyzhb *mail:    [email protected] *2014-1-12  Nanjing,njupt,China */public class Userinfo {/** * {field : ‘yhm‘,title : ‘username‘,width : 150}, {field : ‘pwd‘,title : ‘password‘,width : 150},{field : ‘yhqx‘,title : ‘使用者權限‘,width : 150}, {field : ‘zcsj‘,title : ‘注冊時間‘,width : 150},{field : ‘bz‘,title : ‘備忘‘,width : 180}] ]; */private String id;private String yhm;private String pwd;private String yhqx;private String zcsj;private String bz;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getYhm() {return yhm;}public void setYhm(String yhm) {this.yhm = yhm;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getYhqx() {return yhqx;}public void setYhqx(String yhqx) {this.yhqx = yhqx;}public String getZcsj() {return zcsj;}public void setZcsj(String zcsj) {this.zcsj = zcsj;}public String getBz() {return bz;}public void setBz(String bz) {this.bz = bz;}}

DataGrid類

/* * $filename: DataGrid.java,v $ * $Date: 2013-10-11  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testaa;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2013-10-11  Nanjing,njupt,China */public class DataGrid{    private int total;    private Userinfo[] rows;public Userinfo[] getRows() {return rows;}public void setRows(Userinfo[] rows) {this.rows = rows;}public int getTotal() {return total;}public DataGrid(int total, Userinfo[] rows) {this.total = total;this.rows = rows;}public DataGrid( ) {}public void setTotal(int total) {this.total = total;}}

ErrorHandler

/* * $filename: ErrorHandlerForUserService.java,v $ * $Date: 2014-4-29  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.example.testaa;import org.androidannotations.annotations.EBean;import org.androidannotations.annotations.RootContext;import org.androidannotations.annotations.UiThread;import org.androidannotations.api.rest.RestErrorHandler;import org.springframework.web.client.RestClientException;import android.content.Context;import android.util.Log;import android.widget.Toast;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-4-29  Nanjing,njupt,China */@EBeanpublic class MyErrorHandler implements RestErrorHandler {@RootContextContext context;@Overridepublic void onRestClientExceptionThrown(RestClientException e) {// TODO Auto-generated method stube.printStackTrace();Log.d("REST", e.toString());showError();}@UiThreadvoid showError(){Toast.makeText(context, "Rest Error...", Toast.LENGTH_SHORT).show();}}

剩下的就是MainActivity

package com.example.testaa;import org.androidannotations.annotations.AfterViews;import org.androidannotations.annotations.Background;import org.androidannotations.annotations.Bean;import org.androidannotations.annotations.Click;import org.androidannotations.annotations.EActivity;import org.androidannotations.annotations.UiThread;import org.androidannotations.annotations.ViewById;import org.androidannotations.annotations.rest.RestService;import org.springframework.http.ResponseEntity;import android.app.Activity;import android.util.Log;import android.widget.Button;import android.widget.TextView;/* *@author: ZhengHaibo   *web:     http://blog.csdn.net/nuptboyzhb *mail:    [email protected] *2014-4-15  Nanjing,njupt,China */@EActivity(R.layout.activity_main)public class MainActivity extends Activity {private static final String TAG="AAREST";@ViewByIdButton getUser;@ViewByIdTextView myTextView;@RestServiceUserService userService;@BeanMyErrorHandler  errorHandlerForUserService;@AfterViewsvoid afterView(){//設定ErrorHandleruserService.setRestErrorHandler(errorHandlerForUserService);}/** * 擷取使用者列表 */@Clickvoid getUser() {getUserInBackground();}/** * 擷取使用者列表 * 無需登入 */@Backgroundvoid getUserInBackground(){//String result = userService.getUserInfoList();//Gson gson = new Gson();//DataGrid  dataGrid = gson.fromJson(result, DataGrid.class);ResponseEntity<DataGrid> responseEntiy = userService.getUserInfoList();if(null == responseEntiy){return;}DataGrid  dataGrid = responseEntiy.getBody();Userinfo[] userinfos= dataGrid.getRows();String string = "";for(Userinfo userinfo:userinfos){string = string + "user:"+ userinfo.getYhm();Log.d(TAG, userinfo.getYhm());}Log.d(TAG, string);displayTextView(string);}@UiThreadvoid displayTextView(String string){myTextView.setText(string);}}


總結:

整個項目使用AndroidAnnotation架構。本次部落客要解決服務端和android進行json互動的情況。

缺點:Response的setContentType設定改動後,可能影響原網站對瀏覽器的支援,因此,須要依據不同情境進行選擇。

整個項目:http://download.csdn.net/detail/nuptboyzhb/7283863

未經同意,不得用於商業目的


Androidannotation使用之@Rest與server互動的JSON資料轉換(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.