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; }}}
}

View Code

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 = 0;}catch (Exception ex){response.Code = -1;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(1);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 = 0;}catch (Exception ex){response.Code = -1;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 = 0;}catch (Exception ex){response.Code = -1;response.Msg = ex.Message;}return Json(response, "text/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);}}
}

View Code

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; }}        }
}

View Code

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> {@Overridepublic 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;}
}

View Code

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 blockthrow 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,取得HttpResponseHttpResponse 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);}}
}

View Code

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;}
}

View Code

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;
}

View Code

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", "8"));String json = HttpClientUtil.get("http", "122.226.151.4", 7086,"/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", 7086,"/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", 7086,"/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", "8"));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);}
}

View Code

Android Gson 操作相关推荐

  1. Android 常用操作

    0.android studios使用介绍 使用介绍 android studio 常用小技巧 网址 1.怎么样添加第三方库 方法一:第一步:将第三方库以module的形式导入 第二步:选中要导入第三 ...

  2. Android Gson在Kotlin data class中的使用

    文章目录 Android Gson在Kotlin data class中的使用 基本使用 NEP 空指针异常问题 空指针异常产生的原因 空安全失效问题 字段全有默认值 字段部分有默认值 解决问题 使用 ...

  3. Android 文件操作

    Android 文件操作操作时,要赋予相应的权限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_S ...

  4. Android SDCard操作(文件读写,容量计算)

    Android SDCard操作(文件读写,容量计算) android.os.Environment 提供访问环境变量 java.lang.Object android.os.Environment ...

  5. android的文件操作,Android文件操作概要1.ppt

    Android文件操作概要1 Linux文件系统 在Linux中,文件的扩展名并不重要,一个文件是否可以访问或执行,是完全由文件属性来决定的.细心的读者会发现最后一列比较特殊,这一列描述的是Linux ...

  6. android jxl.jar 使用,使用jxl.jar在Android中操作Excel表格——重中之重——对隐藏表的处理...

    曾简单了解过C#,将Excel(数据库表)表中的数据导入到C#中,使用C#制作的图形化界面进行对Excel表中数据进行操作. 今天想试试,在Android中导入Excel表格进行操作.在网上查阅资料, ...

  7. Android数据库操作-1

    Android采用关系型数据库SQLite3,它是一个支持SQL轻量级的嵌入式数据库,在嵌入式操作系统上有很广泛的应用,WM采用的也是SQLite3<?xml:namespace prefix ...

  8. Android自定义操作栏示例教程

    In this tutorial we will create an app that consists of Android Custom Action Bar with a custom layo ...

  9. Android键盘操作的函数:onKeyDown, onKeyUp, on, onKeyMultiple

    android Activity类onKeyUp() ,onKeyDown 略读 Activity.onKeyDown(); 当某个键被按下时会触发,但不会被任何的该Activity内的任何view处 ...

最新文章

  1. MegEngine 框架设计
  2. 三分频的Verilog实现
  3. Oracle:推迟了的Java Enterprise Edition 8将会在“今年之内”发布
  4. 融合通信常见问题3月刊 | 云信小课堂
  5. keil C 51 strlen库函数使用
  6. 算法竞赛入门经典(第二版) | 例题5-1 大理石在哪 (普适查找)(UVa10474,Where is the Marble?)
  7. php ppt read_php怎么读取ppt文字内容并在浏览器中显示出来?
  8. 【数值分析】证明题一道
  9. .NET Web实时消息后台服务器推送技术-GoEasy
  10. kali无法共享本机文件_MySQL服务端读取客户端文件漏洞的复现
  11. 简析 JSON 中的{}与[]
  12. CCF201312-3 最大的矩形(解法二)(100分)(废除!!!)
  13. No usable temporary directory found in [‘/tmp‘, ‘/var/tmp‘, ‘/usr/tmp‘]
  14. 005-OpenStack-网络服务
  15. 中国大湾区经济推动新全球化时代
  16. 如何提高人际交往的沟通技巧
  17. Sky Hackthon比赛指北-基础篇
  18. python 批量转换docx只转换了一个出现pywintypes.com_error被调用的对象已与其客户端断开连接
  19. 高精度加法 高精度减法 高度除法 高精度乘法 方法总结
  20. 域名该怎样选_给项目选择域名时我们常犯的几个错误 我们应该如何正确选择域名...

热门文章

  1. 一沙一世界,一花一天堂
  2. kpu 处理器_KPU · MaixPy 文档
  3. 四川大地震将是中国社会的转折点
  4. 课程设计——网上商店前台功能的设计与实现
  5. LQ0076 既约分数【GCD】
  6. 计算机大师( 一 ) COMPUTER MASTERS (1)
  7. 字节跳动张一鸣:给互联网人才的一些中肯建议!
  8. ForkJoinPool 大型图文现场
  9. 类似蘑菇街、迷尚的流瀑布图片展示Demo
  10. 市场调研—全球与中国实验室压片机市场现状及未来发展趋势