Maryam
Maryam

Reputation: 515

Extract Items in Nested Json Array

How can I extract items from nested Json Array using Newtonsoft.Json functions or methods? I have a Json like this

{
  "Bounds": {
    "TextLength": 1379
  },
  "DocumentTypeName": "Invoice",
  "DocumentTypeField": {
    "Value": "Invoice",
    "Confidence": 1
  },
  "Fields": [
    {
      "FieldId": "RPA.DocumentUnderstanding.Invoice.LineItems",
      "FieldName": "Line Items",
      "Values": [
        {
          "Components": [
            {
              "FieldId": "RPA.DocumentUnderstanding.Invoice.LineItems.Body",
              "FieldName": "Body",
              "Values": [
                {
                  "Components": [
                    {
                      "FieldId": "RPA.DocumentUnderstanding.Invoice.LineItems.Item",
                      "FieldName": "Item",
                      "Values": [
                        {
                          "Components": [],
                          "Value": "Film 4C for the publication \"Racing World\" Visual: PNSP 02 05 Ref. 2004/021 Graphic designer honoraries 560010",
                          "Confidence": 0.962736368
                        }
                      ]
                    },
                    {
                      "FieldId": "RPA.DocumentUnderstanding.Invoice.LineItems.UnitPrice",
                      "FieldName": "Unit Price",
                      "Values": [
                        {
                          "Components": [],
                          "Value": "400.00",
                          "Confidence": 0.9779528
                        }
                      ]
                    }
                  ],
                  "Confidence": 0.9432406
                }]}],
          "Confidence": 0.920952857}]}]}

and I want to extract the red highlighted fields from it.

enter image description here

Any help will be much appreciated.

Thanks

Upvotes: 0

Views: 200

Answers (2)

Stanislav
Stanislav

Reputation: 460

You can use JSON Query

Example

var fieldNames = o.SelectTokens("Values[*].Components[*].Values[*].Components[*].FieldName");

Upvotes: 0

dogyear
dogyear

Reputation: 308

Since not deserializing is not a requirement you can do that. Just create C# object that has the exact same structure as your JSON and then do

var yourObject = JsonConvert.DeserializeObject<YourCSharpClassHere>(yourJsonString);

Then it's just a simple matter of getting the values

var fieldName = yourObject.Values[0].Components[0].Values[0].Components[0].FieldName

Upvotes: 1

Related Questions