ABC
ABC

Reputation: 345

Tell Json.Net deserialize JArray into class property

I'm new to C# and start trying to use Json.Net! I have this JSON:

{
    "id": "foobar",
    "stuff": {
      "inside": {
        "insideProperty": "Hello, World!",
        "insideProperty2": "Foo and Bar!"
      }
    },
    "myArray": [
      {
        animal: "Cat"
      },
      {
        animal: "Dog",
        typeOfFood: "Meat"
      }
    ]
}

I have these class:

class MyModel {
  [JProperty("id")]
  public string Id {get; set;}

  [JProperty("insideProperty")]
  public string InsideProperty {get; set;}

  [JProperty("insideProperty2")]
  public string InsideProperty2 {get; set;}

  // [What should I put here so Json.net can deserialize an array?]
  // What is the correct data type here? MyArrayModel[] or IList<MyArrayModel>
  public MyArrayModel MyArrays {get; set;}
}
class MyArrayModel {
  [JProperty("animal")]
  public string Animal {get; set;}

  [JProperty("typeOfFood")]
  public string TypeOfFood {get; set;}
}

I'm really curious, how can I make Json.Net automatically set the MyModel.MyArray correctly? Without I have to manually read the JArray and do it myself?

Thank you!

Upvotes: 0

Views: 231

Answers (1)

pinkfloydx33
pinkfloydx33

Reputation: 12799

First, let's answer your asked questions:

  • The attribute is JsonPropertyAttribute, not JProperty
  • You would use JsonProperty("myArray") on your MyArrays property
  • You can either use MyArrayModel[] or List<MyArrayModel>, whichever makes more sense for you

That said, your MyModel class is wrong! The insideProperty and insideProperty2 properties are not a part of the root MyModel object. They are properties of a sub-object's sub-object! Your actual classes should look more like this:

public class MyModel
{
    [JsonProperty("id")]
    public string Id { get; set; } 

    [JsonProperty("stuff")]
    public Stuff Stuff { get; set; } 

    [JsonProperty("myArray")]
    public List<MyArrayModel> MyArrays { get; set; } 
}

public class Stuff 
{
    [JsonProperty("inside")]
    public Inside Inside { get; set; } 
}

public class Inside 
{
    [JsonProperty("insideProperty")]
    public string InsideProperty { get; set; } 

    [JsonProperty("insideProperty2")]
    public string InsideProperty2 { get; set; } 
}

public class MyArrayModel
{
    [JsonProperty("animal")]
    public string Animal { get; set; } 

    [JsonProperty("typeOfFood")]
    public string TypeOfFood { get; set; } 
}

I strongly suggest using a website such as json2csharp.com or using Visual Studio's "paste JSON as classes" feature.

Upvotes: 2

Related Questions