I tried to find a solution for deserializing an anonymous object from JSON to a structure resembling the original JSON structure in ServiceStack.Text, but I did not find any acceptable solution. While I do understand that the deserializer does not have a clue about how to deserialize a generic object, I am ready to indicate it some rules like:
I tried to deserialize to a Dictionary<string, object>, but the entries are all strings, no matter if I have complex object inside or not, or even lists. The next try was with ExpandoObject, which was a little better, recognizing the lists as List<object>, but the objects inside are all strings. I assumed that for the scenario with the two rules indicated above it should be a simple configuration issue, but I did not find any possibility.
Does anyone have a clue in solving this puzzle? Thanks in advance.
It seems that the following settings do the trick:
JsConfig.ConvertObjectTypesIntoStringDictionary = true;
JsConfig.TryToParsePrimitiveTypeValues = false; // otherwise, for untyped jsons, any string value which can't be converted to primitive types will return null.
var dictionary = ServiceStack.Text.JsonSerializer.DeserializeFromString(json, typeof(object));
Another option would be the DynamicJson
class provided by ServiceStack.Text, but the implementation does not preserve the original names from the JSON.
For an alternative implementation, check the JsonExpando class in Kephas Framework (https://github.com/quartz-software/kephas/blob/master/src/Kephas.Serialization.ServiceStack.Text/JsonExpando.cs). Important: use the above settings in JsonConfig
.