您如何使用 Newtonsoft 解析对象数组?

How do you parse an array of objects with Newtonsoft?

我只是想把这个 JSON 变成某种对象。 JArray 和 JToken 完全让我困惑。

我可以创建一个 class 以便 Newtonsoft 知道要映射到什么,但是如果您注意到对象具有以下结构:{ "anAnimal": { foo: 1, bar: 2 }} 并且知道映射器对象的外观。我很确定这应该立即起作用,我的想法为零。

var myFavoriteAnimalsJson = @"
[
    {
        ""Dog"": {
            ""cuteness"": ""7.123"",
            ""usefulness"": ""5.2"",
        }
    },
    {
        ""Cat"": {
            ""cuteness"": ""8.3"",
            ""usefulness"": ""0"",
        }
    }
]";

var jArray = new JArray(myFavoriteAnimalsJson);
// grab the dog object. or the cat object. HOW CUTE IS THE DOG? 

如果您从序列化的 JSON 开始,即字符串,您必须解析它:

var jArray = JArray.Parse(myFavoriteAnimalsJson);

.SelectToken()构建JSON路径查询逻辑。

下面的示例查询 animals 的第一项以获取“狗”标记的对象及其值。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

JArray animals = JArray.Parse(myFavoriteAnimalsJson);
        
var dog = animals[0].SelectToken("Dog");

Console.WriteLine(dog);
Console.WriteLine(dog["cuteness"]);

Sample Program

输出

{ "cuteness": "7.123", "usefulness": "5.2" }

7.123

您可以将其反序列化为 List<Dictionary<string, AnimalData>>

class AnimalData
{
    public decimal cuteness;
    public decimal usefulness;
}
var myFavoriteAnimalsJson = @"
[
    {
        ""Dog"": {
            ""cuteness"": ""7.123"",
            ""usefulness"": ""5.2"",
        }
    },
    {
        ""Cat"": {
            ""cuteness"": ""8.3"",
            ""usefulness"": ""0"",
        }
    }
]";

var results = JsonConvert.DeserializeObject<List<Dictionary<string, AnimalData>>>(myFavoriteAnimalsJson);

现在每个列表项都包含一个字典,其中一个键为 Dog Cat...