Last active
July 20, 2018 18:15
-
-
Save lfgrando/88aa4a5bd0811ed5786f6ab650bde2fb to your computer and use it in GitHub Desktop.
Replace custom matched token on JToken
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
public static class JTokenExtensions | |
{ | |
private JToken LookupPreviousData(string value, JToken resourceToken) | |
{ | |
if (!resourceToken.HasValues) | |
return null; | |
if (!Regex.Match(value, ProjectionMatch).Success) | |
return null; | |
var match = value.Substring(value.IndexOf("$response")); | |
return resourceToken.SelectToken(value.Substring(match.Length < ProjectionMatch.Length ? match.Length : ProjectionMatch.Length)); | |
} | |
private JToken ApplyProjection(JToken result) | |
{ | |
if (Project == null) | |
return result; | |
Project.ReplaceMatchToken(result, LookupPreviousData); | |
return Project; | |
} | |
public static void ReplaceMatchToken(this JToken replaceToken, JToken resourceToken, Func<string, JToken, JToken> lookupToken) | |
{ | |
if (replaceToken.Type == JTokenType.Array) | |
{ | |
foreach (JToken child in replaceToken.Children()) | |
ReplaceMatchToken(child, resourceToken, lookupToken); | |
} | |
else if (replaceToken.Type == JTokenType.Object) | |
{ | |
foreach (JProperty property in replaceToken.Children<JProperty>()) | |
{ | |
if (property.Value.Type == JTokenType.String) | |
{ | |
var value = lookupToken(property.Value.ToString(), resourceToken); | |
if (value != null) | |
property.Value.Replace(value); | |
// | |
continue; | |
} | |
ReplaceMatchToken(property.Value, resourceToken, lookupToken); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment