CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class Program
{
static string GetJson()
{
var json = @"{
""?xml"" : {
""@version"" : ""1.0"",
""@encoding"" : ""UTF-8""
},
""DataFeed"" : {
""@FeedName"" : ""AdminData"",
""People"" : [{
""id"" : ""63"",
""active"": ""1"",
""firstName"" : ""Joe"",
""lastName"" : ""Schmoe"",
""roleIds"" : {
""int"" : ""4""
}
} , {
""id"" : ""65"",
""active"": ""1"",
""firstName"" : ""Steve"",
""lastName"" : ""Jobs"",
""roleIds"" : {
""int"" : [""4"", ""16"", ""25"", ""20"", ""21"", ""22"", ""17"", ""23"", ""18""]
}
} , {
""id"" : ""66"",
""active"": ""1"",
""firstName"" : ""Bill"",
""lastName"" : ""Gates"",
""roleIds"" : {
""int"" : [""3"", ""16"", ""25"", ""20""]
}
}, {
""id"" : ""666"",
""active"": ""1"",
""firstName"" : ""Non"",
""lastName"" : ""Person"",
""roleIds"" : {
}
}
]
}
}";
return json;
}
public static void Main()
{
var jsonString = GetJson();
JObject jsonFeed = JObject.Parse(jsonString);
int desiredRoleId = 4;
var query = from people in jsonFeed.SelectTokens("DataFeed.People")
.SelectMany(i => i)
let ids = people
.SelectToken("roleIds.int")
.SingleOrMultiple()
.Select(t => (int)t)
.ToArray()
where (int?)people["active"] == 1 && ids.Contains(desiredRoleId)
select new
{
Id = (int)people["id"],
FirstRoleId = ids.FirstOrDefault(),
ResAnFName = (string)people["firstName"],
ResAnLName = (string)people["lastName"]
};
Console.WriteLine("Query result: ");
Console.WriteLine(JsonConvert.SerializeObject(query, Formatting.Indented));
}
}
public static class JsonExtensions
{
public static IEnumerable<JToken> SingleOrMultiple(this JToken source)
{
if (source == null)
return Enumerable.Empty<JToken>();
IEnumerable<JToken> arr = source as JArray;
return arr ?? new[] { source };
}
}