Search code examples
c#jsonservicestack-text

ServiceStack.Text json serializer deserializes raw string with brackets as jsv


I have some JSON text and I want to deserialize it into a Dictionary<string, object>. ServiceStack.Text does that no problem, until there are brackets inside the string values. Then it decides to deserialize that string, as if it was JSV (ServiceStack's format, similar to json but without quotes).

Here is a simplified JSON example:

{
  "prop1": "value1",
  "prop2": "{tag} value2"
}

And the code:

JsConfig.Init(new Config
{
    ConvertObjectTypesIntoStringDictionary = true,
});
            
// json variable is a string, read from a file
var tree = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json);

This is the mangled result I get (back in json form):

{
  "prop1": "value1",
  "prop2": {
    "tag}": "alue2"
  }
}

This only happens when the curly bracket is directly after the quotation mark.

Newtonsoft serializer works as expected in this case, but I don't really want make a switch, if I can find a solution or a workaround.


Solution

  • ServiceStack.Text's JSON Serializer is primarily designed for deserializing JSON into typed POCOs.

    For deserializing artibtrary JSON into untyped collections it's recommended to use JS Utils instead, e.g:

    var obj = (Dictionary<string, object>)JSON.parse(json);