您的位置:首页 > 移动开发 > Android开发

Androidannotation使用之@Rest与服务器交互的JSON数据转换(二)

2014-05-02 17:13 465 查看
开篇
之前的一篇博客: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: zhb931706659@126.com
*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: zhb931706659@126.com
*2014-1-12 Nanjing,njupt,China
*/
public class Userinfo {
/**
* {field : 'yhm',title : '用户名',width : 150},
{field : 'pwd',title : '密码',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: zhb931706659@126.com
*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: zhb931706659@126.com
*2014-4-29 Nanjing,njupt,China
*/
@EBean
public class MyErrorHandler implements RestErrorHandler {

@RootContext
Context context;

@Override
public void onRestClientExceptionThrown(RestClientException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Log.d("REST", e.toString());
showError();
}

@UiThread
void 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: zhb931706659@126.com
*2014-4-15 Nanjing,njupt,China
*/
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {

private static final String TAG="AAREST";
@ViewById
Button getUser;

@ViewById
TextView myTextView;

@RestService
UserService userService;

@Bean
MyErrorHandler errorHandlerForUserService;

@AfterViews
void afterView(){
//设置ErrorHandler
userService.setRestErrorHandler(errorHandlerForUserService);
}
/**
* 获取用户列表
*/
@Click
void getUser() {
getUserInBackground();
}
/**
* 获取用户列表
* 无需登录
*/
@Background
void 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);
}

@UiThread
void displayTextView(String string){
myTextView.setText(string);
}
}


总结:
整个项目使用AndroidAnnotation框架。本次博客主要解决服务端和android进行json交互的情况。
缺点:Response的setContentType设置修改后,可能影响原网站对浏览器的支持,因此,需要根据不同场景进行选择。
整个项目下载地址:http://download.csdn.net/detail/nuptboyzhb/7283863未经允许,不得用于商业目的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: