2012-10-16 46 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