using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using uzai.tools;
using Newtonsoft.Json;
namespace CodeTest.test8
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//json 反序列化1
string jsonString1 = "{\"Age\":28,\"Name\":\"张三\"}";
Person p1 = JsonHelper.JsonDeserialize<Person>(jsonString1);
//json 反序列化2
string jsonString = "[{treeId:13938,treeName:\"海洋水手号\"},{treeId:19955,treeName:\"内舱房\",imgId:19603,imgName:\"内舱房\"},{treeId:17929,treeName:\"济州蓝色海岸\"}]";
List<tree> p = Newtonsoft.Json.JsonConvert.DeserializeObject<List<tree>>(jsonString);
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
public class tree
{
public int treeId { get; set; }
public string treeName { get; set; }
public int imgId { get; set; }
public string imgName { get; set; }
}
}
}
方法1使用的 Jsonhelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
namespace uzai.tools
{
/// <summary>
/// JSON序列化和反序列化辅助类
/// </summary>
public class JsonHelper
{
/// <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();
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
}
方法2 需要引用 Newtonsoft.Json.dll
下载地址: