近来属的私单是一个CS项目,里面有着的操作都是经过调用API接口来进展的。

接口详细说明

磋商: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类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Converters;

namespace BarCounter.Util
{
    /// <summary>
    ///JsonUtility 的摘要说明
    /// </summary>
    public class Utility
    {
        /// <summary>
        /// Json工具类
        /// </summary>
        public static class JsonUtility
        {
            /// <summary>
            /// 添加时间转换器
            /// </summary>
            /// <param name="serializer"></param>
            private static void AddIsoDateTimeConverter(JsonSerializer serializer)
            {
                IsoDateTimeConverter idtc = new IsoDateTimeConverter();
                //定义时间转化格式
                idtc.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                //idtc.DateTimeFormat = "yyyy-MM-dd";
                serializer.Converters.Add(idtc);
            }

            /// <summary>
            /// Json转换配置
            /// </summary>
            /// <param name="serializer"></param>
            private static void SerializerSetting(JsonSerializer serializer)
            {
                serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
            }

            /// <summary>
            /// 返回结果消息编码
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="sucess"></param>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="data"></param>
            /// <returns></returns>
            public static string ReturnMessage(bool sucess, int total, string message, string exMessage, string data)
            {
                message = message.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", "");
                exMessage = exMessage.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", "");

                return string.Format("{{success:{0},total:{1},data:{2},message:\"{3}\",exMessage:\"{4}\"}}",
                    sucess.ToString().ToLower(), total, data, message, exMessage);
            }

            /// <summary>
            /// 返回失败信息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <returns></returns>
            public static string ReturnFailureMessage(string message, string exMessage)
            {
                return ReturnMessage(false, 0, message, exMessage, "[]");
            }

            /// <summary>
            /// 返回失败信息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <returns></returns>
            public static string ReturnFailureMessageTouch(string message, string exMessage)
            {
                return "{\"success\":\"false\",\"msg\":\"" + exMessage + "\"}";
            }

            /// <summary>
            /// 返回成功信息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="total"></param>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="objList"></param>
            /// <returns></returns>
            public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, List<T> objList)
            {
                string data = ListToJson<T>(objList);
                return ReturnMessage(true, total, message, exMessage, data);
            }

            public static string ReturnSuccessMessageTouch<T>(T obj)
            {
                string data = ObjectToJson<T>(obj);
                return data;
            }

            /// <summary>
            /// 返回成功信息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="total"></param>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="objList"></param>
            /// <returns></returns>
            public static string ReturnSuccessMessage(string message, string exMessage)
            {
                return ReturnMessage(true, 0, message, exMessage, "[]");
            }

            /// <summary>
            /// 返回成功信息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="total"></param>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="objList"></param>
            /// <returns></returns>
            public static string ReturnSuccessMessageTouch(string message, string exMessage)
            {
                return "{\"success\":\"true\",\"msg\":\"" + message + "\"}";
            }



            /// <summary>
            /// 返回成功信息
            /// </summary>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="data">JSON 对象</param>
            /// <returns></returns>
            public static string ReturnSuccessMessage(string message, string exMessage, string data)
            {
                return ReturnMessage(true, 0, message, exMessage, "[" + data + "]");
            }

            /// <summary>
            /// 返回成功消息
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="total"></param>
            /// <param name="message"></param>
            /// <param name="exMessage"></param>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, T obj)
            {
                string data = ObjectToJson<T>(obj);
                return ReturnMessage(true, total, message, exMessage, data);
            }

            /// <summary>
            /// 把对象列表编码为Json数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="objList"></param>
            /// <returns></returns>
            public static string ListToJson<T>(List<T> objList)
            {
                JsonSerializer serializer = new JsonSerializer();
                SerializerSetting(serializer);
                AddIsoDateTimeConverter(serializer);

                using (TextWriter sw = new StringWriter())
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, objList);
                    return sw.ToString();
                }
            }

            /// <summary>
            ///  把一个对象编码为Json数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string ObjectToJson<T>(T obj)
            {
                JsonSerializer serializer = new JsonSerializer();
                SerializerSetting(serializer);
                AddIsoDateTimeConverter(serializer);

                using (TextWriter sw = new StringWriter())
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, obj);
                    return sw.ToString();
                }
            }


            /// <summary>
            /// 根据传入的Json数据,解码为对象(一个)
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="data"></param>
            /// <returns></returns>
            public static T DecodeObject<T>(string data)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                AddIsoDateTimeConverter(serializer);
                StringReader sr = new StringReader(data);
                return (T)serializer.Deserialize(sr, typeof(T));


            }

            /// <summary>
            /// 功能同DecodeObject
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="data"></param>
            /// <returns></returns>
            public static List<T> DecodeObjectList<T>(string data)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                AddIsoDateTimeConverter(serializer);
                StringReader sr = new StringReader(data);
                return (List<T>)serializer.Deserialize(sr, typeof(List<T>));
            }

            public static string EncodeAjaxResponseJson(string jsonString, string callback)
            {
                String responseString = "";
                //判断是否jsonp调用
                if (!String.IsNullOrEmpty(callback))
                {
                    //jsonp调用,需要封装回调函数,并返回
                    responseString = callback + "(" + jsonString + ")";
                }
                else
                {
                    //普通ajax调用,直接返回Json数据
                    responseString = jsonString;
                }

                return responseString;
            }

            public static string ExtGridSortInfo(string property, string direction)
            {
                return string.Format("[{{\"property\":\"{0}\",\"direction\":\"{1}\"}}]", property, direction);
            }
        }
    }
}

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

 

相关文章

网站地图xml地图