I have an object which is being returned as a payload of content for another via an API.
Some of the properties of the object (which is complex and can contain lists of other objects, lists of different types, etc.) can contain placeholder values which I need to swap for the correct values before the object is returned.
Currently, to keep it simple, I am serializing the object to a string, running a custom replace function on said string to replace all placeholder instances, and then I am deserializing the string back to an object so it's in the correct format for the site that's going to consume it. This works, and as I am generally able to get a response from the API in less than 10ms, I am not worried about performance loss from serializing/deserializing the object to achieve my goal.
However, I have since found that some of the placeholders may be nested within others, so my approach no longer holds up. I have found that using the LINQ Aggregate()
function, nested placeholder values are correctly replaced, and it's still performant:
public string ReplacePlaceholderValues(string source, Dictionary<string, string> placeholders)
{
var replacedText = placeholders.Aggregate(source, (current, replacement) =>
{
return current.Replace(replacement.Key, replacement.Value);
});
return replacedText;
}
My issue comes when I need to deserialize the string back to an object. If a nested placeholder contains say double-quotes, JsonConvert.Deserialize
breaks with "unexpected character was encountered", which is expected.
I can change the above method:
public string ReplacePlaceholderValues(string source, Dictionary<string, string> placeholders)
{
var replacedText = placeholders.Aggregate(source, (current, replacement) =>
{
return current.Replace(replacement.Key, JsonConvert.SerializeObject(replacement.Value(replacement.Value));
});
return replacedText;
}
but this will wrap all my strings in double-quotes, which is also no good.
Can anyone suggest a way around this to fix the formatting of nested placeholders (preferable solution).
I am open to suggestions for changing how this works, I have toyed with the idea of reflection to do a string replace on all string properties on the initial object, forgoing serialization/deserialization completely, but this could be quite complicated (due to nested classes, lists of nested classes, etc.) and will need reflection as the object could be quite complex and I want this to be a pretty generic solution where different objects can be manipulated, hence going down the route of serializing the object first.
Here is a fiddle of essentially what is happening. My page payload object is more complex etc. etc.:
https://dotnetfiddle.net/eKHxwn
(Feel free to point out any obvious issues, beyond the primary one, I am likely suffering with tunnel vision...)