Androidannotation using @rest JSON Data transformation to interact with server (ii)

Source: Internet
Author: User

Opening

Previous blog: androidannotation use of @rest access to resources and user login verification (a): http://blog.csdn.net/nupt123456789/article/details/24384713 The main write is that rest is required to jsession the field when the user logs on. This blog is mainly written in JSON format conversion.

@Rest documentation for the exam:

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

Brief introduction:

from the previous blog, we can see that we directly re-request in the browser when Http://192.168.0.101:8080/cbvr/getUserInfoList.action, the returned string is actually in JSON format. Our last blog was to treat it directly as a string, without any problems. Of course, we can then parse the string using Gson, which is fine. However, we usually think that we can change a converter is not OK? The code is as follows:

/* * $filename: USERSERVICE.JAVA,V $ * $Date: 2014-4-20 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are 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 ();}

In this way, we use the Gson message converter, of course, the need to import Gson related packages. However, when executing the program, we find an error such as the following:

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/HT Ml;charset=utf-8]

Say what does not have the suitable httpmessageconverter, I thought is the Android side question, changed several converters, the result still error. Then, only to find that the original is not the Android side of the problem, is the server side. Each time the server outputs a JSON string, the following properties are set, for example:

Response.setcontenttype ("Text/html;charset=utf-8");

It turns out that this is the reason, so change the service side to such as the following:

Response.setcontenttype ("Application/json;charset=utf-8");

Then, execute again, OK, done! In this way, we are able to get directly to the object after the conversion to JSON format. In order to add the robustness of the program, ErrorHandler processing is added to it. The rest of the code is as follows:

Package com.example.testaa;/* * @author: Zhenghaibo *WEB:HTTP://BLOG.CSDN.NET/NUPTBOYZHB *github https://github.co M/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: ' User Rights ', width:1 *, {field: ' ZCSJ ', title: ' Register Time ', Width:150},{field: ' BZ ', title: ' Remarks ', 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 class

/* * $filename: DATAGRID.JAVA,V $ * $Date: 2013-10-11  $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are 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 are 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:htt P://BLOG.CSDN.NET/NUPTBOYZHB *mail: [email protected] *2014-4-29 Nanjing,njupt,china */@EBeanpublic class MyErro Rhandler 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 ();}} 

The rest is 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 () {//Set Errorhandleruserservice.setresterrorhandler (Errorhandlerforuserservice);} /** * Get user list */@Clickvoid GetUser () {Getuserinbackground ();}  /** * Get user list * * No login required */@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);d Isplaytextview (string);} @UiThreadvoid Displaytextview (String string) {Mytextview.settext (string);}}


Summarize:

Entire Project use the Androidannotation framework. This blog mainly addresses the situation of JSON interaction between the server and Android.

Disadvantage: Response's setcontenttype settings change, may affect the original site to the browser support, therefore, you need to choose according to different scenarios.

Entire project: http://download.csdn.net/detail/nuptboyzhb/7283863

Not for commercial purposes without consent


Androidannotation using @rest JSON Data transformation to interact with server (ii)

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.