标签:
现在关于json的读写问题,有许许多多的解决方法,因人而异,根据实际问题去选择自己想要的最容易方法。我觉得自带的Newtonsoft.Json是个不错的选择,随便写两个例子吧!
一:关于简单的json序列化和反序列化,可以用Newtonsoft.Json+实体类去解决。
首先搞个jsonhelp类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace SerializationAndDeserialization.Code
{
public class JsonHelp
{
/// <summary>
/// JSON序列化
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//替换Json的Date字符串
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
/// <summary>
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
/// </summary>
private static string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(1970,1,1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
/// <summary>
/// 将时间字符串转为Json时间
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);
return result;
}
}
}
第二步:建两个要用的实体类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SerializationAndDeserialization.Code
{
public class Model1
{
public string code { get; set; }
public string description { get; set; }
}
}
public class Model2
{
public string name { get; set; }
public string age { get; set; }
public string sex { get; set; }
public Love love { get; set; }
}
public class Love
{
public string Play { get; set; }
public string Music { get; set; }
}
然后就是搞个测试案例啦:
1:序列化json:
private void test2()
{
List<Model2> list = new List<Model2>();
Love l = new Love();
l.Music = "音乐";
l.Play = "篮球";
Model2 m = new Model2();
m.name = "小明";
m.age = "18";
m.sex = "男";
m.love = l;
list.Add(m);
Love lo = new Love();
lo.Music = "唱歌";
lo.Play = "跳舞";
Model2 m1 = new Model2();
m1.name = "小王";
m1.age = "19";
m1.sex = "男";
m1.love = lo;
list.Add(m1);
string result = JsonHelp.JsonSerializer<List<Model2>>(list);
Response.Write(result);
}
2:先序列化再反序列化效果:
private void test1()
{
Model1 m = new Model1();
m.code = "00000";
m.description = "成功了";
string result = JsonHelp.JsonSerializer<Model1>(m);
Model1 mm = JsonHelp.JsonDeserialize<Model1>(result);
Response.Write(mm.description + "......" + mm.code);
//Response.Write(result);
}
但是。。。。对于一个如果复杂的json来说,你还想按照json视图去写实体类吗?再说建实体类 个人觉得很麻烦,岂不是不同的json格式就要写一个实体类,不是很好的选择。。。
下面就写个利用Newtonsoft.Json和dynamic类型的组合引用解析json:
json格式为:
{
"SvcCont": [
{
"PUB_REQ": {
"TYPE": "ADD_TEST_BEAN"
},
"result": {
"resultCode": "0",
"resultData": {
"accountNumber": "05519430313",
"areaID": "0001",
"servicetype": 201,
"vbRestValue": 0,
"vbTotalValue": 0
},
"resultMsg": "成功"
}
}
],
"TcpCont": {
"LatnCd": "551",
"ServiceCode": "FUNC99002",
"SrcOrgID": "30",
"SrcSysID": "1030",
"SrcSysSign": "5273C8FD1C9B483A1A8BC49BAF363987",
"TransactionID": "20140709101229"
}
}
下面我就说如何得到:resultCode 和resultMsg的值 !
//模拟json字符串
string ss = "{\"SvcCont\":[{\"PUB_REQ\":{\"TYPE\":\"ADD_TEST_BEAN\"},\"result\":{\"resultCode\":\"0\",\"resultData\":{\"accountNumber\":\"05519430313\",\"areaID\":\"0001\",\"servicetype\":201,\"vbRestValue\":0,\"vbTotalValue\":0},\"resultMsg\":\"成功\"}}],\"TcpCont\":{\"LatnCd\":\"551\",\"ServiceCode\":\"FUNC99002\",\"SrcOrgID\":\"30\",\"SrcSysID\":\"1030\",\"SrcSysSign\":\"5273C8FD1C9B483A1A8BC49BAF363987\",\"TransactionID\":\"20140709101229\"}}";
//一步一步去解析,根据自己的要求和json格式一层一层反序列化
if (ss.StartsWith("{") && ss.EndsWith("}")
|| ss.StartsWith("[") && ss.EndsWith("]"))
{
dynamic xx = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(ss);
dynamic resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(xx.SvcCont.ToString());
List<dynamic> pags = Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>(resultData.ToString());
foreach (var pag in pags)
{
dynamic pagss = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(pag.result.ToString());
string code = pagss.resultCode.ToString();
string msg = pagss.resultMsg.ToString();
Response.Write("code值为Code:" + code + ",mess的值为:" + msg);
}
}
好了,以上就是简单json序列化和反序列化的问题,希望对你有帮助!
关于json序列化和反序列的问题,没事写个案例,希望能帮到那些需要帮忙的朋友!
标签:
原文地址:http://www.cnblogs.com/zuozongyao/p/4271934.html