Reputation: 684
I have a Json response which contains multiple arrays from which I need to get the last array. I want to select ExpenseDescriptions and return just this to the ajax call using Linq. ExpenseDescription is always the last array returned. The structure of my response is as follows:
{
"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
}
]
}
}
]
}
}
I can use linq to do some basic clauses but can't figure out or find a way that lets me do the above. Any help in doing this with Linq would be appreciated.
Upvotes: 1
Views: 253
Reputation: 3660
Here's a solution using 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());
}
}
}
}
output:
{
"Code": "TRH8",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
}
{
"Code": "VVFT3",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
}
Upvotes: 1