Last active
November 13, 2018 14:14
-
-
Save fredeil/6ac565e22d69a920063ffea302cac717 to your computer and use it in GitHub Desktop.
Transform json objects in .NET using JSON.NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result is: