C# Winform反序列化复杂json字符串
最近接的私单是一个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”:””,"errcode":”,”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 = ;
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 + , 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, , 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, , 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, , 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);
}
}
}
}
调用方式:
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);
}
C# Winform反序列化复杂json字符串的更多相关文章
- Newtonsoft.Json.dll反序列化JSON字符串的方法
1.直接反序列化JSON字符串 //引用序列化.反序列化JSON字符串用到的空间 using Newtonsoft.Json; using Newtonsoft.Json.Linq; //定义一个 ...
- Newtonsoft.Json.dll 反序列化JSON字符串
上一篇JSON博客<JSON入门级学习小结--JSON数据结构>中已对JSON做了简单介绍,JSON字符串数组数据样式大概是这样子的: 如今因为项目需求(asp.net web网站,前台向 ...
- C#解析JSON字符串总结
JSON文件读取到内存中就是字符串,.NET操作JSON就是生成与解析JSON字符串. 操作JSON通常有以下几种方式: 1. 原始方式:按照JSON字符串自己来解析. 2. 通用方式[★★★★★]: ...
- C#解析JSON字符串总结(转载)
JSON文件读取到内存中就是字符串,.NET操作JSON就是生成与解析JSON字符串. 操作JSON通常有以下几种方式: 1. 原始方式:按照JSON字符串自己来解析. 2. 通用方式[★★★★★]: ...
- 序列化与反序列化之JSON
在不同编程语言之间传递对象,须把对象序列化为标准格式,比如XML 但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可被所有语言读取,也可方便地存储到磁盘或者通过网络传输 JSON不 ...
- C# JSON字符串序列化与反序列化
JSON与c#对象转换http://hi.baidu.com/donick/item/4d741338870c91fe97f88d33 C# JSON字符串序列化与反序列化 – http://www. ...
- .NET中如何使用反序列化JSON字符串/序列化泛型对象toJsonStr
在进行 .NET Web MVC 框架开发的网站程序的时候,我们都会遇到最关键的问题,数据传输. .NET MVC 4中的ControllerBase类建议我们用ViewBag动态数据字典形式(t ...
- JSON字符串序列化与反序列化浅试
一.添加引用(using Newtonsoft.Json.Linq;) 二. 1.生成json字符串源码 List<string> list = new List<string> ...
- c# .net 读取json 字符串 与序列化和反序列化json字符串
命名空间 using Newtonsoft.Json.Linq; JObject obj = JObject.Parse("json字符串");用 obj["" ...
随机推荐
- python开启简单webserver
python开启简单webserver linux下面使用 python -m SimpleHTTPServer 8000 windows下面使用上面的命令会报错,Python.Exe: No Mod ...
- Zookeeper-Zookeeper client
当我写完Zookeeper leader选举后,准备看看Zookeeper的存储和处理客户端请求的时候发现,如果能看看Zookeeper的API是不是在理解后面的过程更好些呢. Zookeeper的c ...
- win10 svchost.exe (LocalSystemNetworkRestricted)大量读写数据
博主的笔记本联想Y50开机完毕后会不停滴读硬盘/写硬盘,导致开机后一段时间内无法正常使用电脑(硬盘读写高峰期).打开资源监视器发现是"svchost.exe (LocalSystemNetw ...
- 24个 HTML5 & CSS3 下拉菜单效果及制作教程
下拉菜单是一个很常见的效果,在网站设计中被广泛使用.通过使用下拉菜单,设计者不仅可以在网站设计中营造出色的视觉吸引力,但也可以为网站提供了一个有效的导航方案.使用 HTML5 和 CSS3 可以更容易 ...
- 把图片加载到BufferedImage中
把图片加载到BufferedImage 中有什么作用呢?它就可以利用 ImageIO.write(image, "JPEG", response.getOutputStream() ...
- [SDK2.2]Windows Azure Cloud Service (35) 使用VS2013发布Azure Cloud Service
<Windows Azure Platform 系列文章目录> 好久没有更新BLOG了,今天我们继续Windows Azure相关的内容. 笔者最近把Visual Studio升级到了20 ...
- Azure上七层负载均衡APP Gateway
Azure的SLB和ILB是最常用的4层负载均衡工具.但有些场景是7层的负载均衡,SLB和ILB就无能为力了. Azure上已经推出了APP Gateway的服务,就是7层负载均衡的负载均衡器. 如上 ...
- 【数据压缩】Huffman编码
1. 压缩编码概述 数据压缩在日常生活极为常见,平常所用到jpg.mp3均采用数据压缩(采用Huffman编码)以减少占用空间.编码\(C\)是指从字符空间\(A\)到码字表\(X\)的映射.数据压缩 ...
- Elasticsearch 连接查询
在一般的关系型数据库中,都支持连接操作. 在ES这种分布式方案中进行连接操作,代价是十分昂贵的. 不过ES也提供了相类似的操作,支持水平任意扩展,实现连接的效果. 其他内容,参考Elasticsear ...
- laravel中的错误与日志
日志 laravel中的日志是基于monolog而封装的.laravel在它上面做了几个事情: 把monolog中的addInfo等函数简化成为了info这样的函数 增加了useFiles和useDa ...