2012-10-16 48 views
1

我有一个Json响应,其中包含多个数组,我需要从中获取最后一个数组。我想选择ExpenseDescriptions并使用Linq将它返回给ajax调用。 ExpenseDescription始终是返回的最后一个数组。我的回应的结构如下:使用Linq从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 
        } 
       ] 
      } 
     } 
    ] 
} 
} 

我可以使用LINQ做一些基本条款,但不能找出或找到一种方法,让我做以上。任何帮助与Linq这样做将不胜感激。

+0

什么是你解析JSON的方式是什么?你是指C#中的Linq吗? –

+0

@DmitryLedentsov,是的,我的意思是Linq在C#中。解析Json不是问题。谢谢。 – KDee

+1

请参阅下面的答案。消化成一行:'var last_array = jsonobject.Descendants()。Last(x => x.Type == JTokenType.Array);' –

回答

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 
} 
+0

谢谢,那1行'var last_array = jsonobject.Descendants()。Last(x => x.Type == JTokenType.Array);'诀窍。完美的作品! – KDee