使用Linq从Json响应中获取最后一个数组

时间:2012-10-16 10:46:53

标签: json linq

我有一个Json响应,它包含多个数组,我需要从中获取最后一个数组。我想选择ExpenseDescriptions并使用Linq将其返回到ajax调用。 ExpenseDescription始终是返回的最后一个数组。我的回应结构如下:

{
"Data": {
    "Items": [
        {
            "Result": {
                "Id": "Some Data"
            }
        },
        {
            "Result": {
                "Id": "Some More Data"
            }
        },
        {
            "Result": {
                "ExpenseDescriptions": [
                    {
                        "Code": "TRH8",
                        "Description": "Some Description",
                        "UnitCost": 0,
                        "MaxThreshold": 0,
                        "MinThreshold": 0
                    },
                    {
                        "Code": "VVFT3",
                        "Description": "Some Description",
                        "UnitCost": 0,
                        "MaxThreshold": 0,
                        "MinThreshold": 0
                    }
                ]
            }
        }
    ]
}
}

我可以使用linq做一些基本的条款,但无法找出或找到一种方法让我做上述事情。任何与Linq合作的帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是使用Newtonsoft.Json.Linq的解决方案:

using System;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{'Data': {
    'Items': [
        {
            'Result': {
                'Id': 'Some Data'
            }
        },
        {
            'Result': {
                'Id': 'Some More Data'
            }
        },
        {
            'Result': {
                'ExpenseDescriptions': [
                    {
                        'Code': 'TRH8',
                        'Description': 'Some Description',
                        'UnitCost': 0,
                        'MaxThreshold': 0,
                        'MinThreshold': 0
                    },
                    {
                        'Code': 'VVFT3',
                        'Description': 'Some Description',
                        'UnitCost': 0,
                        'MaxThreshold': 0,
                        'MinThreshold': 0
                    }
                ]
            }
        }
    ]
}
}";
            JObject jsonobject = JObject.Parse(json);

            var last_array = jsonobject.Descendants().Last(x => x.Type == JTokenType.Array);

            foreach (var e in last_array)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

输出:

{
  "Code": "TRH8",
  "Description": "Some Description",
  "UnitCost": 0,
  "MaxThreshold": 0,
  "MinThreshold": 0
}
{
  "Code": "VVFT3",
  "Description": "Some Description",
  "UnitCost": 0,
  "MaxThreshold": 0,
  "MinThreshold": 0
}