我有一个名为ShipFromAddress
的具体类,我在下面的方式反序列化我的json
JavaScriptSerializer jss = new JavaScriptSerializer();
oShipFromAddress = jss.Deserialize<ShipFromAddress>(Request.Cookies["ShipFromAddress"].Value);
具体课程
public class ShipFromAddress
{
public string Weight
{
get;
set;
}
public string addressLine1
{
get;
set;
}
public string addressLine2
{
get;
set;
}
public string city
{
get;
set;
}
public string postcode
{
get;
set;
}
public string countrycode
{
get;
set;
}
public string StateCode
{
get;
set;
}
}
我不想创建或使用具体类,而是希望在动态对象或匿名类概念的帮助下动态地进行反序列化。请引导我提供示例代码。
1)当需要将多个数据序列化传递给匿名时,示例将是
var query = from employee in employees select new { Name = employee.Name, Id = employee.Id };
LogEmployees(query);
public void LogEmployees (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}
方法参数类型必须是IEnumerable<dynamic> because LogEmployees()
函数,需要多个数据
2)传递单个数据时,代码看起来像
public class Program
{
private static void Thing(dynamic other)
{
Console.WriteLine(other.TheThing);
}
private static void Main()
{
var things = new { TheThing = "Worked!" };
Thing(things);
}
}
答案 0 :(得分:4)
使用JavaScriptSerializer,您可以使用序列化程序中的DeserializeObject
方法,它只返回一个对象:
JavaScriptSerializer jss = new JavaScriptSerializer();
object obj= jss.DeserializeObject(Request.Cookies["ShipFromAddress"].Value);
在内部,它将被表示为Dictionary<string, object>
,因此您可以将其投射到它并使用如下:
var values = (Dictionary<string, object>)jss.DeserializeObject(Request.Cookies["ShipFromAddress"].Value);
var addressLine1 = values["addressLine1"].ToString();
或者您可以将其投放到dynamic
:
dynamic values = jss.DeserializeObject(Request.Cookies["ShipFromAddress"].Value);
var addressLine1 = values["addressLine1"].ToString();
或者,您可以使用Json.NET
库及其JsonConvert
类(基准测试表明它的执行速度比JavaScriptSerializer
快)。代码如下所示:
dynamic values = JsonConvert.DeserializeObject(Request.Cookies["ShipFromAddress"].Value);
var addressLine1 = values.addressLine1;
答案 1 :(得分:3)
我使用Newtonsoft.Json
string source = Request.Cookies["ShipFromAddress"].Value as string;
var address = JsonConvert.DeserializeObject<ShipFromAddress>(source);