/// <summary>
/// Json帮助类
/// </summary>
public class JsonHelper
{
/// <summary>
/// 将对象序列化为JSON格式
/// </summary>
/// <param name="o">对象</param>
/// <returns>json字符串</returns>
public static string SerializeObject(object o)
{
string json = JsonConvert.SerializeObject(o);
return json;
}
/// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
/// <typeparam name="T">匿名对象类型</typeparam>
/// <param name="json">json字符串</param>
/// <param name="anonymousTypeObject">匿名对象</param>
/// <returns>匿名对象</returns>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
View Code
为进一步理解Newtonsoft,写了一些测试的例子:
/// <summary>
/// Json测试
/// </summary>
public class JsonTest : IRun
{
public void Run()
{
Student sdudent = new Student();
sdudent.ID = 1;
sdudent.Name = "陈晨";
sdudent.NickName = "石子儿";
sdudent.Class = new Class() { Name = "CS0216", ID = 0216 };
//实体序列化和反序列化
string json1 = JsonHelper.SerializeObject(sdudent);
//json1 : {"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}}
Student sdudent1 = JsonHelper.DeserializeJsonToObject<Student>(json1);
//实体集合序列化和反序列化
List<Student> sdudentList = new List<Student>() { sdudent, sdudent1 };
string json2 = JsonHelper.SerializeObject(sdudentList);
//json: [{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}},{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}}]
List<Student> sdudentList2 = JsonHelper.DeserializeJsonToList<Student>(json2);
//DataTable序列化和反序列化
DataTable dt = new DataTable();
dt.TableName = "Student";
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name");
dt.Columns.Add("NickName");
DataRow dr = dt.NewRow();
dr["ID"] = 112;
dr["Name"] = "战三";
dr["NickName"] = "小三";
dt.Rows.Add(dr);
string json3 = JsonHelper.SerializeObject(dt);
//json3 : [{"ID":112,"Name":"战三","NickName":"小三"}]
DataTable sdudentDt3 = JsonHelper.DeserializeJsonToObject<DataTable>(json3);
List<Student> sdudentList3 = JsonHelper.DeserializeJsonToList<Student>(json3);
//验证对象和数组
Student sdudent4 = JsonHelper.DeserializeJsonToObject<Student>("{\"ID\":\"112\",\"Name\":\"石子儿\"}");
List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]");
//匿名对象解析
var tempEntity = new { ID = 0, Name = string.Empty };
string json5 = JsonHelper.SerializeObject(tempEntity);
//json5 : {"ID":0,"Name":""}
tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity);
var tempStudent = new Student();
tempStudent = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempStudent);
Console.Read();
}
}
/// <summary>
/// 学生信息实体
/// </summary>
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string NickName { get; set; }
public Class Class { get; set; }
}
/// <summary>
/// 学生班级实体
/// </summary>
public class Class
{
public int ID { get; set; }
public string Name { get; set; }
}
View Code
使用Json帮助类时,有两点需要注意下:
1. 通常使用调用实体序列化SerializeObject()和反序列化DeserializeJsonToObject()两个方法就可以了。但有些情况下我们解析json字符串时,可能没有对应的实体类型(或者说不想添加对应的实体类),这时候可以用匿名对象解析方法DeserializeAnonymousType(),方便快捷,对应代码如下:
//匿名对象解析
var tempEntity = new { ID = 0, Name = string.Empty };
string json5 = JsonHelper.SerializeObject(tempEntity);
//json5 : {"ID":0,"Name":""}
tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity);
Console.WriteLine(tempEntity.ID + ":" + tempEntity.Name);
2. Json的两种结构数组和对象解析时略有不同。Json对象一般转换成实体,Json数组一般转换成实体集合。代码如下:
//验证对象和数组
Student sdudent4 = JsonHelper.DeserializeJsonToObject<Student>("{\"ID\":\"112\",\"Name\":\"石子儿\"}");
List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]");
简单解释下Json对象和数组的含义:
对象是以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间运用 “,”(逗号)分隔。名称用引号括起来;值如果是字符串则必须用括号,数值型则不须要。
例如:{"ID":"112","Name":"石子儿"}。
数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间运用 “,”(逗号)分隔。
例如:[{"ID":"112","Name":"石子儿"},{"ID":"113","Name":"陈晨"}]。
你们的评论、反馈,及对你们有所用,是我整理材料和博文写作的最大的鼓励和唯一动力。欢迎讨论和关注!
没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。