告诉 Json.Net 将 JArray 反序列化为 class 属性

Tell Json.Net deserialize JArray into class property

我是 C# 新手,开始尝试使用 Json.Net!我有这个 JSON:

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

我有这些 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;}
}

我很好奇,如何让Json.Net自动正确设置MyModel.MyArray?无需我手动读取 JArray 并自己完成?

谢谢!

首先,让我们回答您提出的问题:

  • 属性是JsonPropertyAttribute不是JProperty
  • 您将在 MyArrays 属性
  • 上使用 JsonProperty("myArray")
  • 您可以 使用 MyArrayModel[]List<MyArrayModel>, 哪个对您更有意义

也就是说,你的MyModelclass是错误的insidePropertyinsideProperty2 属性不是 root MyModel 对象的一部分。它们是子对象的子对象的属性!您的实际 classes 应该更像这样:

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; } 
}

我强烈建议使用 json2csharp.com 之类的网站或使用 Visual Studio 的“将 JSON 粘贴为 classes”功能。