Android Gson 操作
JSON序列化后的数据不带类名与名命空间,所以这两个服务端跟客户端可以不对应,需要保证字段对应即可
Asp.net MVC端
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace cn.fstudio.hessian.dto
- {
- public class ResponseBase<T>
- {
- private int code;
- private string msg;
- private T model;
- public int Code
- {
- get { return code; }
- set { code = value; }
- }
- public string Msg
- {
- get { return msg; }
- set { msg = value; }
- }
- public T Model
- {
- get { return model; }
- set { model = value; }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using cn.fstudio.hessian.dto;
- using cn.fstudio.update.model;
- using AA.DAO;
- using System.Text;
- using EmitMapper;
- namespace AA.Web.Controllers
- {
- public class SoftController : Controller
- {
- //
- // GET: /Soft/
- /// <summary>
- /// 获取列表
- /// </summary>
- /// <returns></returns>
- public ActionResult Index()
- {
- var response = new ResponseBase<List<SoftInfo>>();
- try
- {
- using (var ctx = DBCtx.GetCtx())
- {
- response.Model= ObjectMapperManager.DefaultInstance.GetMapper<List<Base_Soft>,List<SoftInfo>>().Map(ctx.Base_Soft.ToList());
- }
- response.Code = ;
- }
- catch (Exception ex)
- {
- response.Code = -;
- response.Msg = ex.Message;
- }
- return Json(response,"text/json",Encoding.UTF8,JsonRequestBehavior.AllowGet );
- }
- public ActionResult GetApp(String id,String v)
- {
- using (var ctx = DBCtx.GetCtx())
- {
- int softId=int.Parse(id);
- var q = ctx.Base_SoftVersion.Where(ent => ent.SoftId == softId);
- if (!String.IsNullOrWhiteSpace(v))
- {
- q = q.Where(ent => ent.VersionCode == v);
- }
- q = q.OrderByDescending(ent => ent.VersionCode).Take();
- var it= q.FirstOrDefault();
- if (it == null)
- {
- throw new Exception("未找到该软件!");
- }
- var soft= ctx.Base_Soft.FirstOrDefault(ent => ent.SoftId == softId);
- return File(Server.MapPath(it.Path), "application/vnd.android", Url.Encode(string.Format("{0}_{1}.apk",soft.FileName,it.VersionCode)));
- }
- }
- public ActionResult AppVers(String id)
- {
- var response = new ResponseBase<List<SoftVersionInfo>>();
- try
- {
- using (var ctx = DBCtx.GetCtx())
- {
- var list= ctx.ExecuteStoreQuery<SoftVersionInfo>("Select SoftId,RecId,VersionName,VersionCode,AddTime From Base_SoftVersion Where SoftId={0} order by versionCode desc",id).ToList();
- response.Model = list;
- }
- response.Code = ;
- }
- catch (Exception ex)
- {
- response.Code = -;
- response.Msg = ex.Message;
- }
- return Json(response, "text/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
- }
- public ActionResult AppLastVer(String id)
- {
- var response = new ResponseBase<SoftVersionInfo>();
- try
- {
- using (var ctx = DBCtx.GetCtx())
- {
- var it = ctx.ExecuteStoreQuery<SoftVersionInfo>("Select Top 1 SoftId,RecId,VersionName,VersionCode,AddTime From Base_SoftVersion Where SoftId={0} order by versionCode desc,RecId desc", id).FirstOrDefault();
- response.Model = it;
- }
- response.Code = ;
- }
- catch (Exception ex)
- {
- response.Code = -;
- response.Msg = ex.Message;
- }
- return Json(response, "text/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace cn.fstudio.update.model
- {
- public class SoftInfo
- {
- private int softId;
- private string softName;
- private string versionName;
- private string versionCode;
- private DateTime addTime;
- private DateTime lastTime;
- private string memo;
- private int recId;
- private String fileName;
- public String FileName
- {
- get { return fileName; }
- set { fileName = value; }
- }
- /// <summary>
- /// SoftId
- /// </summary>
- public int SoftId
- {
- get { return softId; }
- set { softId = value; }
- }
- /// <summary>
- /// SoftName
- /// </summary>
- public string SoftName
- {
- get { return softName; }
- set { softName = value; }
- }
- /// <summary>
- /// VersionName
- /// </summary>
- public string VersionName
- {
- get { return versionName; }
- set { versionName = value; }
- }
- /// <summary>
- /// VersionCode
- /// </summary>
- public string VersionCode
- {
- get { return versionCode; }
- set { versionCode = value; }
- }
- /// <summary>
- /// AddTime
- /// </summary>
- public DateTime AddTime
- {
- get { return addTime; }
- set { addTime = value; }
- }
- /// <summary>
- /// LastTime
- /// </summary>
- public DateTime LastTime
- {
- get { return lastTime; }
- set { lastTime = value; }
- }
- /// <summary>
- /// Memo
- /// </summary>
- public string Memo
- {
- get { return memo; }
- set { memo = value; }
- }
- /// <summary>
- /// RecId
- /// </summary>
- public int RecId
- {
- get { return recId; }
- set { recId = value; }
- }
- }
- }
android端
- package cn.fstudio.update;
- import java.lang.reflect.Type;
- import java.util.Date;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import com.google.gson.FieldNamingPolicy;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import com.google.gson.JsonDeserializationContext;
- import com.google.gson.JsonDeserializer;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonParseException;
- public class GsonUtil {
- public static class DateDeserializer implements JsonDeserializer<Date> {
- @Override
- public Date deserialize(JsonElement json, Type typeOfT,
- JsonDeserializationContext context) throws JsonParseException {
- String JSONDateToMilliseconds = "/Date\\((.*?)\\)/";
- Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
- String value = json.getAsJsonPrimitive().getAsString();
- Matcher matcher = pattern.matcher(value);
- String result = matcher.replaceAll("$1");
- return new Date(new Long(result));
- }
- }
- public static Gson getGson() {
- GsonBuilder gsonb = new GsonBuilder();
- DateDeserializer ds = new DateDeserializer();
- gsonb.registerTypeAdapter(Date.class, ds);
- gsonb.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
- Gson gson = gsonb.create();
- return gson;
- }
- }
- package cn.fstudio.util;
- import java.net.URI;
- import java.net.URISyntaxException;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.CookieStore;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.protocol.ClientContext;
- import org.apache.http.client.utils.URIUtils;
- import org.apache.http.client.utils.URLEncodedUtils;
- import org.apache.http.impl.client.BasicCookieStore;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.protocol.BasicHttpContext;
- import org.apache.http.protocol.HttpContext;
- import org.apache.http.util.EntityUtils;
- import android.R.string;
- import android.util.Log;
- public class HttpClientUtil {
- private static HttpContext httpContext;
- static {
- // 创建一个本地Cookie存储的实例
- CookieStore cookieStore = new BasicCookieStore();
- // 创建一个本地上下文信息
- httpContext = new BasicHttpContext();
- // 在本地上下问中绑定一个本地存储
- httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
- }
- public static String get(String baseUrl,String path,List<NameValuePair> qparams){
- try {
- URI uri=new URI(baseUrl);
- return get(uri.getScheme(), uri.getHost(), uri.getPort(), path, qparams);
- } catch (URISyntaxException e) {
- // TODO Auto-generated catch block
- throw new RuntimeException(e);
- }
- }
- public static String get(String scheme,String host,int port,String path, List<NameValuePair> qparams){
- URI uri=null;
- try {
- if(qparams==null)qparams=new ArrayList<NameValuePair>();
- uri = URIUtils.createURI(scheme, host, port, path, URLEncodedUtils.format(qparams, "UTF-8"), null);
- Log.d("Test", uri.toString());
- return get(uri.toString());
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
- public static String get(String url){
- try {
- // HttpGet连接对象
- HttpGet httpRequest = new HttpGet(url);
- // 取得HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 请求HttpClient,取得HttpResponse
- HttpResponse httpResponse = httpClient.execute(httpRequest,httpContext);
- // for (org.apache.http.Header h : httpResponse.getAllHeaders()) {
- // Log.d("Test",h.getName());
- // }
- // 请求成功
- int statusCode=httpResponse.getStatusLine().getStatusCode();
- if ( statusCode == HttpStatus.SC_OK) {
- HttpEntity entity=httpResponse.getEntity();
- // 取得返回的字符串
- String strResult = EntityUtils.toString(entity);
- entity.consumeContent();
- ////httpClient.getConnectionManager().shutdown();
- return strResult;
- }
- throw new RuntimeException("网络请求执行错误,响应码:" +statusCode);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- package cn.fstudio.update;
- import java.io.Serializable;
- import java.util.Date;
- public class SoftInfo implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private int softId;
- private String softName;
- private String versionName;
- private String versionCode;
- private Date addTime;
- private Date lastTime;
- private String memo;
- private int recId;
- private String fileName;
- public int getSoftId() {
- return softId;
- }
- public void setSoftId(int softId) {
- this.softId = softId;
- }
- public String getSoftName() {
- return softName;
- }
- public void setSoftName(String softName) {
- this.softName = softName;
- }
- public String getVersionName() {
- return versionName;
- }
- public void setVersionName(String versionName) {
- this.versionName = versionName;
- }
- public String getVersionCode() {
- return versionCode;
- }
- public void setVersionCode(String versionCode) {
- this.versionCode = versionCode;
- }
- public Date getAddTime() {
- return addTime;
- }
- public void setAddTime(Date addTime) {
- this.addTime = addTime;
- }
- public Date getLastTime() {
- return lastTime;
- }
- public void setLastTime(Date lastTime) {
- this.lastTime = lastTime;
- }
- public String getMemo() {
- return memo;
- }
- public void setMemo(String memo) {
- this.memo = memo;
- }
- public int getRecId() {
- return recId;
- }
- public void setRecId(int recId) {
- this.recId = recId;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
- }
- package cn.fstudio.update;
- import java.io.Serializable;
- public class ResponseBase<T> implements Serializable{
- private static final long serialVersionUID = 1L;
- public int getCode() {
- return code;
- }
- public void setCode(int code) {
- this.code = code;
- }
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public T getModel() {
- return model;
- }
- public void setModel(T model) {
- this.model = model;
- }
- private int code;
- private String msg;
- private T model;
- }
- package cn.fstudio.test;
- import java.lang.reflect.Type;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.NameValuePair;
- import org.apache.http.message.BasicNameValuePair;
- import com.google.gson.Gson;
- import com.google.gson.reflect.TypeToken;
- import android.util.Log;
- import cn.fstudio.update.GsonUtil;
- import cn.fstudio.update.ResponseBase;
- import cn.fstudio.update.SoftInfo;
- import cn.fstudio.update.SoftVersionInfo;
- import cn.fstudio.util.HttpClientUtil;
- import junit.framework.TestCase;
- public class UpdateTest extends TestCase {
- final String TAG = "Test";
- public void testHttpClient() {
- List<NameValuePair> qparams = new ArrayList<NameValuePair>();
- qparams.add(new BasicNameValuePair("id", ""));
- String json = HttpClientUtil.get("http", "122.226.151.4", ,
- "/soft/AppLastVer", qparams);
- Type type = new TypeToken<ResponseBase<SoftVersionInfo>>(){}.getType();
- Gson gson=GsonUtil.getGson();
- ResponseBase<SoftVersionInfo> response= gson.fromJson(json, type);
- Log.d(TAG, json);
- }
- public void testSoft() {
- String json = HttpClientUtil.get("http", "122.226.151.4", ,
- "/soft/", null);
- Gson gson=GsonUtil.getGson();
- Type type = new TypeToken<ResponseBase<List<SoftInfo>>>(){}.getType();
- ResponseBase<List<SoftInfo>> response= gson.fromJson(json, type);
- Log.d(TAG, json);
- }
- public void testAppVers() {
- List<NameValuePair> qparams = new ArrayList<NameValuePair>();
- qparams.add(new BasicNameValuePair("id", "22a"));
- String json = HttpClientUtil.get("http", "122.226.151.4", ,
- "/soft/appVers", qparams);
- Gson gson=GsonUtil.getGson();
- Type type = new TypeToken<ResponseBase<List<SoftVersionInfo>>>(){}.getType();
- ResponseBase<List<SoftVersionInfo>> response= gson.fromJson(json, type);
- Log.d(TAG, json);
- }
- public void testAppLastVer() {
- List<NameValuePair> qparams = new ArrayList<NameValuePair>();
- qparams.add(new BasicNameValuePair("id", ""));
- String json = HttpClientUtil.get("http://122.226.151.4:7086/",
- "/soft/appLastVer", qparams);
- Gson gson=GsonUtil.getGson();
- Type type = new TypeToken<ResponseBase<SoftVersionInfo>>(){}.getType();
- ResponseBase<SoftVersionInfo> response= gson.fromJson(json, type);
- Log.d(TAG, json);
- }
- }
Android Gson 操作的更多相关文章
- Android 常用操作
0.android studios使用介绍 使用介绍 android studio 常用小技巧 网址 1.怎么样添加第三方库 方法一: 第一步:将第三方库以module的形式导入 第二步:选中要导入第 ...
- [Android Pro] 完美Android Cursor使用例子(Android数据库操作)
reference to : http://www.ablanxue.com/prone_10575_1.html 完美 Android Cursor使用例子(Android数据库操作),Androi ...
- Android – 学习操作NFC – 2
在<Android – 学习操作NFC – 1>说明了Android在处理NFC tag的机制.tag dispatch system的运作流程,以及三种ACTION_NDEF_DISCO ...
- JSON和GSON操作json数据
1,JSON操作json import net.sf.json.JSONArray; import net.sf.json.JSONObject; //json操作数据 public static S ...
- 【转】Android Gson的使用
Android Gson 2014 年 05 月 22 日 android 目前的客户端大都有和服务端进行交互,而数据的格式基本就是json了,于是在Android开发中就经常用到json解析,方便的 ...
- android 文件操作类简易总结
android 文件操作类(参考链接) http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html package com.androi ...
- 为什么说android UI操作不是线程安全的
转载于:http://blog.csdn.net/lvxiangan/article/details/17218409#t2 UI线程及Android的单线程模型原则 使用Worker线程 Commu ...
- Android权限操作之uses-permission详解
本文实例讲述了Android权限操作之uses-permission.分享给大家供大家参考,具体如下: 我们在安装Android软件的时候,系统会提示该软件所需要的权限,相对于其他系统,android ...
- Java操作JSON数据(2)--Gson操作JSON数据
Gson是Google公司发布的一个开发源码的Java库,可用于将Java对象转换为JSON字符串,也可用于将JSON字符串转换为对应的Java对象.本介绍下Gson的基本使用方法,包括序列化和反序列 ...
随机推荐
- nats 学习 集群ha 配置
nats 的ha 是一个mesh 的结构,有两个主要的参数 clusters routers 启动三分节点(单机) 共享变量 SERVERS=nats://127.0.0.1:6222,nats: ...
- vs2013突然没有代码提示功能了。
工具->选项->文本编辑器->C++ ->高级->禁用IntelliSense设置 false 然后选确定.
- bzoj 3730 震波——动态点分治+树状数组
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3730 查询一个点可以转化为查询点分树上自己到根的路径上每个点对应范围答案.可用树状数组 f ...
- 再记录一次delete出错的经历
调试的时候进行到delete语句时出现问题,我做的操作是在函数体内用int*申请了N个内存空间,这让我十分纳闷,为什么不能delete呢? 回忆到之前delete出错也遇过一次问题 手动封装OpenC ...
- 远程连接Linux虚拟机上的mysql失败的解决方法
今天在虚拟机Ubuntu上折腾了一晚上mysql,然后试着用java连接,搞了很久都没成功,但是同学配好的Debian上却连接成功了,也就是说我的配置有问题. 折腾了很久,最后还是通过理解异常信息来大 ...
- week3-栈和队列
1.学习总结 2.PTA实验作业 2.1 题目1:7-1 jmu-报数游戏 2.2 设计思路(伪代码或流程图) 2.3 代码截图 2.4 PTA提交列表说明. 答案错误:error少了 !: 非零返回 ...
- MySQL锁之二:锁相关的配置参数
锁相关的配置参数: mysql> SHOW VARIABLES LIKE '%timeout%'; +-----------------------------+----------+ | Va ...
- 1021 docker prometheus监控体系
jmeter plugin监控的信息很少,只有cpu.内存.网络IO,但这些是不够的.例如对于分析mysql数据库的慢查询.最大连接数等更加细密度的信息. 服务端稳定测试的三个前提: 1.应用级别的自 ...
- PHP向客户端广播信息
在网络中数据传播分为:Unicast(单播) , Multicast(多播或者组播) 和 Broadcast(广播).广播和多播仅应用于UDP,它们对需将报文同时传往多个接收者的应用来说十分重要.而 ...
- Hive 体系结构
1.Hive架构与基本组成 下面是Hive的架构图. 图1.1 Hive体系结构 Hive的体系结构可以分为以下几部分: (1)用户接口主要有三个:CLI,Client 和 W ...