首先需要在项目中引用:Newtonsoft.Json.dll
在代码中添加命名空间:using Newtonsoft.Json;
json序列化和反序列化两个重要方法和例子:
JsonConvert.SerializeObject(object value)序列化,它有个重载方法JsonConvert.SerializeObject(object value, params JsonConverter[] converters)
JsonConvert.DeserializeObject(string value, Type type)反序列化,它有个重载方法JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)
首先我们先建一个Person类代码如下:
public class Person { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } }
1.序列化
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Newtonsoft.Json; namespace JSONnet { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person person = new Person(); person.Name = "GoldenEasy"; person.Age = 25; string strSerializeJSON = JsonConvert.SerializeObject(person); Response.Write(strSerializeJSON); } } }
输出结果:{"Name":"GoldenEasy","Age":25}
2.反序列化
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Newtonsoft.Json; namespace JSONnet { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person person = new Person(); person.Name = "GoldenEasy"; person.Age = 25; string strSerializeJSON = JsonConvert.SerializeObject(person); Person user = (Person)JsonConvert.DeserializeObject(strSerializeJSON, typeof(Person)); Response.Write(user.Name); } } }
输出结果:GoldenEasy
也可以使用模板,通过名字获得Json文件
private static T ParseJson<T>(string filename) { try { var filePath = Configs.GetPath(filename); if (!File.Exists(filePath)) return default(T); var content = File.ReadAllText(filePath); return JsonConvert.DeserializeObject<T>(content); } catch (Exception ex) { Logger.Log("File Parse" + ex.Message); return default(T); } }