JDataResultExtensions Class
Definition
- Namespace
- Codebelt.Extensions.Newtonsoft.Json
- Assemblies
- Codebelt.Extensions.Newtonsoft.Json.dll
Extension methods for the JDataResult class.
public static class JDataResultExtensions
- Inheritance
-
JDataResultExtensions
Examples
The following example shows how to parse JSON and flatten its hierarchical structure. When working with complex nested JSON documents—API responses, configuration files, or database exports—developers need to search for specific properties, validate values at any depth, or transform data without writing recursive navigation code. The JDataResultExtensions class provides extension methods to flatten nested structures, extract specific properties or arrays, and process results using standard LINQ queries. This approach transforms JSON navigation from imperative recursion into declarative LINQ queries that are easier to read, maintain, and test. This example demonstrates parsing multi-level JSON with users and tags, then using extension methods to flatten, extract objects by property names, and group array structures:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Codebelt.Extensions.Newtonsoft.Json;
namespace Examples;
class JDataResultExtensionsExample
{
static void Main()
{
var json = """
{
"users": [
{ "id": 1, "name": "Alice", "age": 30 },
{ "id": 2, "name": "Bob", "age": 25 }
],
"tags": ["admin", "user"]
}
""";
var results = JData.ReadAll(json);
var flat = results.Flatten().ToList();
// Demonstrate flattening
foreach (var item in flat)
{
if (!string.IsNullOrEmpty(item.PropertyName))
{
Console.WriteLine($"{item.Path}: {item.Value}");
}
}
// Demonstrate ExtractObjectValues to extract specific properties from objects
flat.ExtractObjectValues("id,name,age", extracted =>
{
var id = extracted["id"].Value;
var name = extracted["name"].Value;
var age = extracted["age"].Value;
Console.WriteLine($"Extracted: id={id}, name={name}, age={age}");
});
// Demonstrate ExtractArrayValues to extract and process arrays separately
flat.ExtractArrayValues("users,tags", extracted =>
{
var userCount = extracted["users"].Count();
var tagCount = extracted["tags"].Count();
Console.WriteLine($"Grouped arrays: found {userCount} users and {tagCount} tags");
});
}
}
Methods
| Name | Description |
|---|---|
| ExtractArrayValues(IEnumerable<JDataResult>, string, Action<IDictionary<string, IEnumerable<JDataResult>>>) | Extracts one or more values from JSON arrays using the specified |
| ExtractObjectValues(IEnumerable<JDataResult>, string, Action<IDictionary<string, JDataResult>>) | Extracts one or more values from JSON objects using the specified |
| Flatten(IEnumerable<JDataResult>) | Flattens the entirety of the JSON hierarchical |