转载

C# Winform反序列化复杂json字符串

最近接的私单是一个CS项目,里面所有的操作都是通过调用API接口来进行的。

接口详细说明

协议:https  请求方式:posthttps://xx.xxx.net/app/clients

提交json 数据包

{ "action":" food_t_list", "data":{ “pageIndex”:”1”, “pageSize”:”20”, “foodGId”:”1”, “storeId”:”1”    } }

返回说明正确时返回JSON数据包:

{    "result": "1",    "data": {      "totalCount": "20",      "pageCount": "3",      “storeId”:”1”,      "foodTables": [        {          "foodTId": "2",          "foodTName": "8号台",          “foodTPeo”:”6”,          “foodGrade”: {“foodGId”:”1”,”foodGName”:”大厅”},          “foodTStatus”:”1”,          "foodTDesc ": "餐桌的描述",          “storeId”:”1”        },        {          "foodTId": "5",          "foodTName": "5号台",          “foodTPeo”:”8”,          “foodGrade”: {“foodGId”:”2”,”foodGName”:”包间”},          “foodTStatus”:”0”,          "foodTDesc ": "餐桌的描述"        }      ]    }  }

错误时返回JSON数据包:

{“result”:”0”,"errcode":10036”,”errmsg":"错误信息!"}   //错误代码,根据代码规则查询错误信息。

根据这个返回的json字符串,我们来构建相应的类FoodList,为后面将json反序列化为FoodList做准备

public abstract class BaseEntity
{
public int result { get; set; }
public int errcode { get; set; }
public string errmsg { get; set; }
}

/// <summary> /// 餐桌列表 /// </summary> public class FoodList : BaseEntity { public FoodEntity data { get; set; } } public class FoodEntity { /// <summary> /// 总页数 /// </summary> public int totalCount { get; set; } /// <summary> /// 当前页数 /// </summary> public int pageCount { get; set; } /// <summary> /// 餐桌等级列表集合 /// </summary> public List<FoodTable> foodTables { get; set; } } public class FoodTable { /// <summary> /// 餐桌 ID /// </summary> public int foodTId { get; set; } /// <summary> /// 餐桌名称 /// </summary> public string foodTName { get; set; } /// <summary> /// 餐桌使用人数 /// </summary> public int foodTPeo { get; set; } /// <summary> /// 餐桌等级 /// </summary> public FoodGradeInfo foodGrade { get; set; } /// <summary> /// 餐桌状态 0 空闲 1 预定 2 使用中 /// </summary> public int? foodTStatus { get; set; } /// <summary> /// 餐桌的描述 /// </summary> public string foodTDesc { get; set; } /// <summary> /// 商铺 ID /// </summary> public int storeId { get; set; } }

那么,我需要做的,就是调用API接口,拿到json字符串,然后反序列化为对象。

C#中序列化和反序列化有多中方式,这里我采用JavaScriptSerializer,在Winform程序中使用JavaScriptSerializer需要先添加如下两个引用:

C# Winform反序列化复杂json字符串

新建HttpClientUtil类,封装API请求的类,

// @POST 方法 public static string PostMethodToString(string metodUrl, string jsonBody) {  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(metodUrl);  request.Method = "post";  request.ContentType = "application/json;charset=UTF-8";  var stream = request.GetRequestStream();  using (var writer = new StreamWriter(stream))  {   writer.Write(jsonBody);   writer.Flush();  }  HttpWebResponse response = (HttpWebResponse)request.GetResponse();  string json = GetResponseString(response);  return json;  //return ((JObject)JsonConvert.DeserializeObject(json)).ToString(); } 

然后新建一个范序列化的类JsonHelper

using System.Web.Script.Serialization;

/// <summary>         /// 把json字符串转成对象         /// </summary>         /// <typeparam name="T">对象</typeparam>         /// <param name="data">json字符串</param>         public static T Deserialize<T>(string data)         {             JavaScriptSerializer json = new JavaScriptSerializer();             return json.Deserialize<T>(data);         }

最后,我们来看调用方法:这里采用了两种调用方式,第一种是直接拼接json字符串,第二种是通过构造强类型类,然后序列化为json字符串

/// <summary>         /// 根据餐桌等级ID获取餐桌列表         /// </summary>         /// <param name="pageIndex"></param>         /// <param name="graId"></param>         /// <returns></returns>         private List<FoodTable> LoadAllData(int pageIndex, int graId)         {  //string jsonBody = "{ 'action': 'food_t_list', 'access_token':'" + CommonProperty.ACCESS_TOKEN +  //  "', 'data': { 'pageIndex': '" + pageIndex + "', 'pageSize': '" + CommonProperty.PageSize + "', 'storeId': " 
+ CommonProperty.StoreId + ",foodGId:'" + graId + "'} }";
//string json = HttpClientUtil.PostMethodToString(CommonProperty.HttpUrl, jsonBody); //List<FoodTable> table = JsonHelper.Deserialize<FoodList>(json).data.foodTables; FoodTListMode mode = new FoodTListMode(); mode.pageIndex = 1; mode.pageSize = CommonProperty.PageSize; mode.foodGId = graId; mode.storeId = CommonProperty.StoreId; DataHelper<FoodList> data = new DataHelper<FoodList>(); List<FoodTable> table = data.LoadData(CommonProperty.FoodTList, mode).data.foodTables; listAll.AddRange(table); FoodList f = new FoodList(); if (table.Count > CommonProperty.PageSize) { LoadAllData(pageIndex + 1, graId); } return listAll; }
正文到此结束
Loading...