使用嵌套对象中的属性反序列化JSON
问题描述:
如何轻松地将此JSON反序列化为OrderDto C#类?有没有办法做到这一点与属性?使用嵌套对象中的属性反序列化JSON
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; }
但它似乎并没有工作。有任何想法吗?谢谢! :)
答
您可以创建另一个类,嵌套属性的其余喜欢如下:
public class OrderDto
{
public string ExternalId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
}
这样做的原因是因为名称是客户对象在JSON数据嵌套属性。
的[JsonProperty("")]
代码通常用于如果JSON名字比名字不同,你想给它的代码,即
[JsonProperty("randomJsonName")]
public string ThisIsntTheSameAsTheJson { get; set; }
答
你的类应该是这样的:
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/
因此,除了引入新的类,没有其他方式?我希望我并不需要引进新的... – bojank
@bojank不受限制,只要我知道了。 C#端必须复制数据以JSON表示的方式。有可能将它转换为键值对的字符串或其他东西,但这可能不是首选。 –
'“客户”:{“名称”:“约翰·史密斯”}'是另一个对象,还有比创造了这个新的对象周围没有其他办法。链接到json2csharp的 – Ric