【问题标题】:Flattening a nested dictionary with System.Text.Json使用 System.Text.Json 展平嵌套字典
【发布时间】:2021-11-25 20:49:31
【问题描述】:

我正在尝试将依赖于Newtonsoft.Json 的最后一段代码移植到System.Text.Json

代码解析 JSON 片段并将其展平。这是由遗留系统生成的,因此我们宁愿尽可能不更改它。

// Comment here including the person who last made a change to the program
[
  // Comment here with the date this value set was changed
  [ "value1", "value2", "value3" ],
  // Comment here with the date this value set was changed
  [ "value1", "value2", "value3" ],
  // Repeat over and over for all data
]

我一直在使用以下代码为 Newtonsoft.Json 解析这个:

using (var sr = new StreamReader(stream))
{
    var array = JArray.Parse(sr.ReadToEnd());
    var flattened = array.SelectMany(x => x).ToArray();

    foreach (var item in flattened)
        items.Add(item.ToObject<string>());
}

上面的代码提取 JSON 有效负载中的每个值,并将它们放入名为 items 的列表中。

如何使用System.Text.Json 解析上述格式的 JSON?

【问题讨论】:

  • 你在问我们什么?
  • @Enigmativity 我认为这很简单,但是我在最后添加了一个问号
  • 您要求我们为您编写代码。这通常是不受欢迎的。您能否向我们展示您所做的尝试以及您在尝试中遇到的问题?
  • 另外,当要求编写代码时,最好为我们提供尽可能多的支持代码。在这种情况下,最好复制、粘贴和运行我们可以看到Newtonsoft.Json 的代码以及您输入的预期输出。
  • 试试这个:var fin = JsonSerializer.Deserialize&lt;string[][]&gt;(jsonDataAsString).SelectMany(x =&gt; x);

标签: c# system.text.json


【解决方案1】:

要将您的代码从Newtonsoft.Json 翻译成System.Txt.Json,您需要执行以下操作:

首先,我看到您正在从流中读取。因此,我将按原样将您的示例转储到 JSON 文件中。然后我会将它读入流中。我也在做这个async:

using (var stream = File.OpenRead("test.json"))
{
    var multiDimentional = await JsonSerializer.DeserializeAsync<string[][]>(
        stream, new JsonSerializerOptions
    {
        AllowTrailingCommas = true,
        ReadCommentHandling = JsonCommentHandling.Skip
    });

    var myArray = multiDimentional.SelectMany(x => x);

    foreach(var i in myArray)
    {
        Console.WriteLine(i);
    }
}

这将输出:

value1
value2
value3
value1
value2
value3

由于您的示例包含 cmets 和尾随逗号,因此我为这些场景添加了例外。

如果您不需要这个async,那么只需删除await 并将DeserializeAsync 更改为Deserialize,而不是从流中读取,您必须先将其读取为字符串.所以:

var jsonAsString = File.ReadAllText("test.json");

var multiDimentional = JsonSerializer.Deserialize<string[][]>(
    jsonAsString, new JsonSerializerOptions
{
    AllowTrailingCommas = true,
    ReadCommentHandling = JsonCommentHandling.Skip
});

var myArray = multiDimentional.SelectMany(x => x);

foreach(var i in myArray)
{
    Console.WriteLine(i);
}

【讨论】:

  • 传奇,感谢您的帮助:)
【解决方案2】:

你的意思是这样的吗?

var data = JsonSerializer.Deserialize<List<List<string>>>(jsonString, new JsonSerializerOptions { AllowTrailingCommas = true });

var flattenData = data.SelectMany(item => item).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2020-11-29
    • 2019-11-15
    • 2012-09-06
    • 1970-01-01
    • 2020-12-24
    • 2019-03-03
    相关资源
    最近更新 更多