C# 迭代 JSON 对象

Bee*_*ion 5 c# json .net-core

我正在尝试使用 .Net Json 反序列化器System.Text.Json来迭代以下 Json 输入。

如果“person_id”是 json 结构中的顶层(见下文),我找到了按“person_id”进行迭代的方法,但我无法找到循环遍历所有下一级项目的方法。

我认为 NewtonSoftJArray和JObject非常接近我所需要的(我可能会追求这一点),但不确定微软的解决方案是否有办法做到这一点......

System.Text.Json微软的库可以做到这一点吗?

{
  "0": {
    "person_id": "0",
    "last_name": "Greg",
    "first_name": "Craig",
  },
  "1": {
    "person_id": "1",
    "last_name": "Doe",
    "first_name": "John",
  }
}
Run Code Online (Sandbox Code Playgroud)

JsonElement通过属性名称提取对象的解决方案(即我可以通过这种方式获取 John Doe 的信息)。

using (JsonDocument document = JsonDocument.Parse(jsonString))
{
    JsonElement root = document.RootElement;

    JsonElement studentsElement = root.GetProperty("1");
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*mes 3

看起来与我之前必须处理的一些 JSON 类似。记住 JSON 对象只是键/值对会有所帮助。

考虑到这一点,您拥有的数据结构可以解释为DictionaryC# 中的 a。

我在我的示例中使用过Newtonsoft.Json,但它们很容易切换到使用System.Text.Json.

最简单的形式,您可以使用:

var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个,Dictionary其中键是"0","1"属性,值是表示内部人员信息的对象。

然后,您可以foreach对字典或其键或值运行一个简单的循环,如下所示:

foreach (var item in dictionary)
{
    var key = item.Key;
    var person = item.Value;
}
Run Code Online (Sandbox Code Playgroud)

但person( item.Value) 仍然只是类型object。

您可以在此处创建一个类来表示每个Person信息,装饰属性以匹配 JSON 数据结构中的内容,如下所示:

public class Person 
{
    [JsonProperty("person_id")]
    public string PersonId { get; set; }
    
    [JsonProperty("first_name")]
    public string FirstName { get; set; }
    
    [JsonProperty("last_name")]
    public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并将 JSON 反序列化为Dictionary<string, Person>:

var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Person>>(jsonString);
Run Code Online (Sandbox Code Playgroud)

这意味着字典中条目的每个值都是 的一个实例Person,您可以访问每个值的强类型属性,如下所示:

foreach (var item in dictionary)
{
    var key = item.Key; // although you probably won't need this
    Console.WriteLine(key);

    var person = item.Value;
    Console.WriteLine(person.PersonId);
    Console.WriteLine(person.FirstName);
    Console.WriteLine(person.LastName);
}

// which gives the following output:
> 0
> 0
> Craig
> Greg
> 1
> 1
> John
> Doe

Run Code Online (Sandbox Code Playgroud)

虽然我在Newtonsoft.Json上面使用过,但是很容易“迁移”上面的示例来使用System.Text.Json.

  • 而不是JsonConvert.DeserializeObject<T>使用JsonSerializer.Deserialize<T>; 和
  • 您可以使用来代替使用[JsonProperty("property_name")]属性[JsonPropertyName("property_name")]。

希望这可以帮助。