使用嵌套对象中的属性反序列化JSON

本文关键字:属性 反序列化 JSON 嵌套 对象 | 更新日期: 2023-09-27 18:20:53

如何轻松地将此JSON反序列化为OrderDto C#类?有没有一种方法可以用属性来实现这一点?

JSON:

{
    "ExternalId": "123",
    "Customer": {
        "Name": "John Smith"
    }
    ...
}

C#:

public class OrderDto
{
    public string ExternalId { get; set; }
    public string CustomerName { get; set; }
    ...
}

我试着摆弄JsonProperty属性,但没能让它发挥作用。我的想法是写一个注释,比如:

[JsonProperty("Customer/Name")]
public string CustomerName { get; set; }

但这似乎并不奏效。有什么想法吗?Thx!:)

使用嵌套对象中的属性反序列化JSON

您的类应该如下所示:

public class OrderDto
{
    public string ExternalId { get; set; }
    public Customer Customer { get; set;}
}
public class Customer
{
    public string CustomerName { get; set; }
}

未来的一个好主意是采用一些现有的JSON并使用http://json2csharp.com/

您可以创建另一个嵌套其余属性的类,如下所示:

public class OrderDto
{
    public string ExternalId { get; set; }
    public Customer Customer { get; set; }
}
public class Customer
{
    public string Name { get; set; }
}

原因是Name是JSON数据中Customer对象的嵌套属性。

如果JSON名称与您希望在代码中给出的名称不同,则通常使用[JsonProperty("")]代码,即

[JsonProperty("randomJsonName")]
public string ThisIsntTheSameAsTheJson { get; set; }