Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON with a property in a nested object [duplicate]

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! :)

like image 847
bojank Avatar asked Nov 05 '15 14:11

bojank


2 Answers

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/

like image 122
Ric Avatar answered Nov 15 '22 11:11

Ric


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; }
like image 37
James Moore Avatar answered Nov 15 '22 12:11

James Moore