首页 技术 正文
技术 2022年11月12日
0 收藏 452 点赞 4,483 浏览 1462 个字

前些日子将项目由使用数据库改版为使用接口,由于接口返回的xml中多了一些附加信息,导致xml转化后的DataTable无法储存在MemCache中。这时可以将xml序列化为其对应的类,当然由于当时对xml的序列化使用不多所以改为接收json转化为对应的类,这里主要展示我如何使用json的。

在接收到传过来的json字符串后,使用JsonConvert.DeserializeObject<T>(string value);转化为相应的类型。于是我写下了需要转化的第一个类型,如下:

   /// <summary>
/// 用于序列化json字符串
/// </summary>
public class JsonSet
{
public string message{set;get;}
public string code { set; get; }
public DataTable entitylist { set; get; } }

  然后改造接口调用中间函数

      private static bool GetJsonSearchData<T>(string param, string url, string method, int length, ref T jsonResult, string encodeWay = "gb2312")
{
bool isSucc = true;
StringBuilder sb = GetSearchData(param, url, method, length, encodeWay);
if (sb != null && sb.Length > )
{
try
{
jsonResult = JsonConvert.DeserializeObject<T>(sb.ToString());
}
catch
{
isSucc = false;
}
}
return isSucc;
}

使用方法如:

   JsonSet jset = new JsonSet();
SearchInterface.PostSearchData<JsonSet>(parms, url, ref jset);
if (jset != null && jset.entitylist != null)
{
return jset.entitylist;
}

由于完全贴合json字符格式创建的类,返回的DataTable格式就是标准的格式,解决了在Memcache中存储的问题。后来在使用中发现原先需要将DataTable转化为相应的对象,如果直接将json转化为相应对象,岂不是要省点事。但项目中所用的类如果都要改造的话改动太多,也不方便,后来发现json字符串相对这些类仅多了code、message两个属性,于是将对象改造为如下

   public  class JsonTList<T>
{
public string code { set; get; }
public string message { set; get; }
public List<T> entitylist { set; get; }
}

使用方式如

    JsonTList<AgtInfoEntity> jT = new JsonTList<AgtInfoEntity>();
SearchInterface.PostSearchData<JsonTList<AgtInfoEntity>>(parms, url, ref jT);
if (jT != null && jT.entitylist != null && jT.entitylist.Count > )
{
agtInfoEntity = jT.entitylist;
CacheManager.Set(cacheName, agtInfoEntity);
}

由此就形成了我们新的接口体系。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289