开篇

之前的一篇博客: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 : '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: 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

未经同意,不得用于商业目的

Androidannotation使用之@Rest与server交互的JSON数据转换(二)的更多相关文章

  1. 深入浅出 Redis client/server交互流程

    综述 最近笔者阅读并研究redis源码,在redis客户端与服务器端交互这个内容点上,需要参考网上一些文章,但是遗憾的是发现大部分文章都断断续续的非系统性的,不能给读者此交互流程的整体把握.所以这里我 ...

  2. ASP.NET MVC与Sql Server交互,把字典数据插入数据库

    在"ASP.NET MVC与Sql Server交互, 插入数据"中,在Controller中拼接sql语句.比如: _db.InsertData("insert int ...

  3. angularjs与server交互

    真正的应用须要和真实的server进行交互,移动应用和新兴的Chrome桌面应用可能是个例外,可是对于此外的全部应用来说,不管你是想把数据持久化到云端.还是须要与其它用户进行实时交互.都须要让应用与s ...

  4. [从源码学设计]蚂蚁金服SOFARegistry 之 如何与Meta Server交互

    [从源码学设计]蚂蚁金服SOFARegistry 之 如何与Meta Server交互 目录 [从源码学设计]蚂蚁金服SOFARegistry 之 如何与Meta Server交互 0x00 摘要 0 ...

  5. iOS解析Server端返回JSON数据

    在做quhao APP架构时,后台Server端使用了Java,提供WebService,而iOS和Android作为移动客户端.在做数据交互时,Server端返回JSON格式数据.由于iOS SDK ...

  6. jQuery form插件的使用--处理server返回的JSON, XML,HTML数据

    详细代码: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> & ...

  7. SQL Server 2008空间数据应用系列二:空间索引(Spatial Index)基础

    原文:SQL Server 2008空间数据应用系列二:空间索引(Spatial Index)基础 在前一篇博文中我们学习到了一些关于地理信息的基础知识,也学习了空间参照系统,既地球椭球体.基准.本初 ...

  8. 玩转Web之Json(二)----jquery easy ui + Ajax +Json+SQL实现前后台数据交互

    最近在学Json,在网上也找过一些资料,觉得有点乱,在这里,我以easy ui的登录界面为例来说一下怎样用Json实现前后台的数据交互 使用Json,首先需要导入一些jar包,这些资源可以在网上下载到 ...

  9. 在ssm框架中前后台数据交互均使用json格式

    前后台数据交互均使用json. 框架ssm(spring+springmvc+mybatis) @RequestBody注解实现接收http请求的json数据,将json数据转换为java对象,注解加 ...

随机推荐

  1. [CSS]background背景

    css背景样式 序号  中文说明  标记语法  1  背景颜色  {background-color:数值}  2  背景图片  {background-image: url('imgpath/img ...

  2. CANoe 入门 Step by step系列(二)CAPL编程【转】

    CAPL就是Communication Application Programming Laguage的缩写,CAPL类似于C语言的语法,因此所有的语法请参考C语言教程,这里不在这里进行详述,关于C语 ...

  3. python中os模块的常用接口和异常中Exception的运用

    1.os.path.join(arg1, arg2) 将arg1和arg2对应的字符串连接起来并返回连接后的字符串,如果arg1.arg2为变量,就先将arg1.arg2转换为字符串后再进行连接. 2 ...

  4. 2016022609 - redis哈希命令集合

    参考:http://www.yiibai.com/redis/redis_hashes.html Redis的哈希值是字符串字段和字符串值之间的映射,所以他们是表示对象的完美数据类型 在Redis中的 ...

  5. Ipv6_Only-b

    网上好多关于ipv6的资料,说半天ipv6是什么,怎么建立测试环境,,,可是没有看到具体的操作和解决的方案,这里,为大家提供一种方案,希望给大家带来帮助吧. 总的来说有三个方面需要进行检查和修改: 1 ...

  6. Quartz1.8.5例子(八)

    /* * Copyright 2005 - 2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the ...

  7. java环境变量设置方法

    1.安装JDK,安装过程中可以自定义安装目录等信息,例如我们选择安装目录为D:\java\jdk1.5.0_08:    2.安装完成后,右击“我的电脑”,点击“属性”:         3.选择“高 ...

  8. RedHat 6.5 离线安装 apache2.4.23

    第一部分:安装gcc等 rpm -ivh mpfr-2.4.1-6.el6.x86_64.rpm rpm -ivh ppl-0.10.2-11.el6.x86_64.rpm rpm -ivh cpp- ...

  9. 【UVA11478】Halum (最短路解差分约束)

    题目: Sample Input2 11 2 102 11 2 -103 31 2 42 3 23 1 54 52 3 44 2 53 4 23 1 01 2 -1Sample OutputInfin ...

  10. Android ServiceConnection类的onServiceDisconnected(ComponentName name)在什么时候执行

    ServiceConnection类中的两个方法非别在服务连接成功时.不成功时调用.其中onServiceDisconnected()方法在连接正常关闭的情况下是不会被调用的, 该方法只在Servic ...