Skip to content

Instantly share code, notes, and snippets.

@fredeil
Last active November 13, 2018 14:14
Show Gist options
  • Save fredeil/6ac565e22d69a920063ffea302cac717 to your computer and use it in GitHub Desktop.
Save fredeil/6ac565e22d69a920063ffea302cac717 to your computer and use it in GitHub Desktop.
Transform json objects in .NET using JSON.NET
using System;
using Newtonsoft.Json.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var original = JObject.Parse(@"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ],
'Results' : [ 1, 2, 3] }");
var template = JObject.Parse(@"{
'FirstName': '',
'Role' : '$.Roles[0]' }");
var result = Process(original, template);
Console.WriteLine(result.ToString());
}
private static JObject Process(JObject original, JObject template)
{
var result = new JObject();
foreach (var property in template.Properties())
{
var value = property.Value?.ToString();
var path = value?.StartsWith("$") == true
? value
: property.Path;
var selected = original.SelectToken(path);
result.Add(property.Name, selected);
}
return result;
}
}
}
@fredeil
Copy link
Author

fredeil commented Nov 13, 2018

Result is:

{
    "FirstName": "John",
    "Role": "User"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment