boj*_*ank 7 c# json json.net deserialization
我如何轻松地将此JSON反序列化为OrderDto C#类?有某种方式可以通过属性来做到这一点吗?
JSON:
{
"ExternalId": "123",
"Customer": {
"Name": "John Smith"
}
...
}
Run Code Online (Sandbox Code Playgroud)
C#:
public class OrderDto
{
public string ExternalId { get; set; }
public string CustomerName { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用JsonProperty属性,但无法使其正常工作。我的想法是写一个像这样的注释:
[JsonProperty("Customer/Name")]
public string CustomerName { get; set; }
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。有任何想法吗?谢谢!:)
您的课程应如下所示:
public class OrderDto
{
public string ExternalId { get; set; }
public Customer Customer { get; set;}
}
public class Customer
{
public string CustomerName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
将来的一个好主意是采用一些现有的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; }
}
Run Code Online (Sandbox Code Playgroud)
原因是 Name 是 JSON 数据中 Customer 对象的嵌套属性。
[JsonProperty("")]如果 JSON 名称与您希望在代码中指定的名称不同,通常会使用该代码,即
[JsonProperty("randomJsonName")]
public string ThisIsntTheSameAsTheJson { get; set; }
Run Code Online (Sandbox Code Playgroud)