Androidannotation use of @rest JSON data conversion with server interaction (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 rest when the user logs on, need to jsession the field of the problem. This blog is mainly written in JSON format conversion.

Reference documentation for @Rest:

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, which, of course, needs to import Gson related packages. However, when running the program, found the following error:

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:

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

It turns out that this is the reason, so the modification of the service side is as follows:

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

Then, run again, OK, done! In this way, we can directly get to the object after the conversion to JSON format. In order to increase the robustness of the program, the ErrorHandler processing is added. The remaining 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: ' User name ', width:150}, {field: ' pwd ', title: ' Password ', Width:150},{field: ' yhqx ', title: ' User Rights ', width:150}, {field : ' ZCSJ ', title: ' Registration 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.

Cons: Response's setcontenttype settings may affect the original web site's browser support, so you need to choose from different scenarios.

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

Not for commercial purposes without permission


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.