How can I easily deserialize this JSON to the OrderDto C# class? Is there a way to do this with attributes somehow?
JSON:
{
"ExternalId": "123",
"Customer": {
"Name": "John Smith"
}
...
}
C#:
public class OrderDto
{
public string ExternalId { get; set; }
public string CustomerName { get; set; }
...
}
I tried playing around with the JsonProperty attribute, but wasn't able to get it work. My ideas were to write an annotation like:
[JsonProperty("Customer/Name")]
public string CustomerName { get; set; }
But it just doesn't seem to work. Any ideas? Thx! :)
Your classes should look like this:
public class OrderDto
{
public string ExternalId { get; set; }
public Customer Customer { get; set;}
}
public class Customer
{
public string CustomerName { get; set; }
}
A good idea in future would be to take some existing JSON and use http://json2csharp.com/
You can create another class that nests the rest of the properties like follows:
public class OrderDto
{
public string ExternalId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
}
The reason for this is because Name is a nested property of the Customer object in the JSON data.
The [JsonProperty("")]
code is generally used if the JSON name is different than the name you wish to give it in code i.e.
[JsonProperty("randomJsonName")]
public string ThisIsntTheSameAsTheJson { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With