1. 程式人生 > >C# Winform反序列化複雜json字串

C# Winform反序列化複雜json字串

協議:https  請求方式:post  
https://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需要先新增如下兩個引用:

新建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; }
複製程式碼

 根據大家的建議,重新試用了下json.net,這次成功了,之前呼叫的方法有問題

方法一、

複製程式碼
      // REST @POST 方法
        public static T DoPostMethodToObj<T>(string metodUrl, string jsonBody)
        {
            request = (HttpWebRequest)WebRequest.Create(metodUrl);
            request.Method = "post";
            request.ContentType = "application/json;charset=UTF-8";
            //request.Connection="keep-alive";

            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 JsonHelper.Deserialize<T>(json);

            return JsonConvert.DeserializeObject<T>(json);
        }
複製程式碼

方法二、新建JsonUtility類

 View Code

呼叫方式:

複製程式碼
     public static T PostMethodToObj<T>(string metodUrl, string jsonBody)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(metodUrl);
            request.Method = "post";
            request.ContentType = "application/json;charset=UTF-8";
            //request.Connection="keep-alive";

            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 Utility.JsonUtility.DecodeObject<T>(json);
         }
複製程式碼