c# - 将 json 反序列化为动态/匿名类 asp.net

标签 c# asp.net json deserialization

我有一个名为 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);
    }
}

最佳答案

借助 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;

关于c# - 将 json 反序列化为动态/匿名类 asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027229/

相关文章:

c# - 如何在列表框中设置多个项目为选中状态?

asp.net - 无法在 IIS(Windows 10)上运行 ASP.net 服务 - 错误 404(未找到)

python - 在 OSX 中通过 curl 美化 JSON

c# - AutoMapper 将目标对象上的属性设置为 null

c# - Entity Framework 试图在数据库中将空字符串保存为 null

python - Pandas - 在数据框中的列中展开嵌套的 json 数组

json - Flutter - 使用 API key

c# - LINQ to SQL 中的错误,数据库上有空字符串

c# - System.DllNotFoundException : 'Unable to load DLL ' libzkfp. dll': The specified module could not be found.(HRESULT 异常:0x8007007E)'

c# - 从 DirectoryInfo.GetFiles 返回的 FileInfo 没有指向文件?