【问题标题】:C# - Parse and read the JSON which has duplicate KeysC# - 解析并读取具有重复键的 JSON
【发布时间】:2018-11-15 17:25:54
【问题描述】:

我试图弄清楚如何解析下面的 JSON 并从中获取 "text": "lawyer"。我看到它有很多分支。即数组和对象。我想在 C# 中执行此操作。这是 JSON:

{
  "status": "Succeeded",
  "succeeded": true,
  "failed": false,
  "finished": true,
  "recognitionResult": {
    "lines": [{
      "boundingBox": [140, 289, 818, 294, 816, 342, 138, 340],
      "text": "General information Com",
      "words": [{
        "boundingBox": [106, 290, 363, 291, 363, 343, 106, 343],
        "text": "General"
      }, {
        "boundingBox": [323, 291, 659, 291, 659, 344, 323, 343],
        "text": "lawyer"
      }, {
        "boundingBox": [665, 291, 790, 291, 790, 344, 665, 344],
        "text": "Com"
      }]
    }]
  }
}

【问题讨论】:

  • 嗨 Karanvir - 这些并不是真正的“重复”,因为每个部分都有自己定义的值,每个部分都可以包含这些值。 words 有自己的boundingBoxtext,但lines 也有,还包含words

标签: c# json parsing


【解决方案1】:

首先使用 Quicktype.io 生成原生 C# 类:

public partial class Result
    {
        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("succeeded")]
        public bool Succeeded { get; set; }

        [JsonProperty("failed")]
        public bool Failed { get; set; }

        [JsonProperty("finished")]
        public bool Finished { get; set; }

        [JsonProperty("recognitionResult")]
        public RecognitionResult RecognitionResult { get; set; }
    }

    public partial class RecognitionResult
    {
        [JsonProperty("lines")]
        public Line[] Lines { get; set; }
    }

    public partial class Line
    {
        [JsonProperty("boundingBox")]
        public long[] BoundingBox { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }

        [JsonProperty("words")]
        public Word[] Words { get; set; }
    }

    public partial class Word
    {
        [JsonProperty("boundingBox")]
        public long[] BoundingBox { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }
    }

然后,deserialize the JSON 使用 Newtonsoft 到 Result 类的一个实例(我们称之为result)。

然后你就可以了

result.RecognitionResult.Where(s => !string.IsNullOrEmpty(s.Text) && s.Text == "lawyer");

如果您只想第一次出现,请使用.FirstOrDefault()

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 2017-02-23
    • 1970-01-01
    • 2018-08-31
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多