-2

I am trying to figure out how I can parse the below JSON and get the "text": "lawyer" out of it. I see that it has to many branching. i.e Arrays and Objects. I want to do this in C#. Here is the 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"
      }]
    }]
  }
}
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • 3
    Possible duplicate of [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Technivorous Nov 15 '18 at 17:30
  • 2
    Hi Karanvir - These aren't really 'duplicates' as each section has its own defined values that each can contain. `words` has `boundingBox` and `text` on its own, but so does `lines` as well, also containing `words`. – gravity Nov 15 '18 at 17:32

1 Answers1

0

First use Quicktype.io to generate a native C# class:

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

Then, deserialize the JSON to an instance of the Result class (let's call it result) using Newtonsoft.

And then you can

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

If you just want the first occurance, use .FirstOrDefault()

Hanjun Chen
  • 544
  • 4
  • 11