21

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
bojank
  • 375
  • 1
  • 3
  • 9

2 Answers2

9

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/

Ric
  • 12,855
  • 3
  • 30
  • 36
  • 4
    that link to json2csharp is very useful. Thank you!!! – Phil Jun 13 '17 at 13:04
  • 5
    This does not answer the question. The question meant deserializing nested objects without creating a new class. – r.mirzojonov Jun 19 '19 at 17:00
  • Very useful comment, thanks. The question already had an answer and was therefore closed as a duplicate. This answer is to provide another possible solution. – Ric Jun 19 '19 at 17:22
0

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; }
James Moore
  • 127
  • 6
  • 14
    So, apart from introducing new classes, there is no other way? I was hoping that I didn't need to introduce new ones... – bojank Nov 05 '15 at 15:02
  • @bojank Not as far as I know. The C# side has to replicate how the data is represented in JSON. It might be possible to convert it to a key-value pair of strings or something but that is probably not preferred. – James Moore Nov 05 '15 at 15:11
  • 2
    `"Customer": {"Name": "John Smith"}` is another object, there is no other way around than creating a new object for this. – Ric Nov 06 '15 at 09:19