Search code examples
c#servicestack-text

ServiceStack.Text DynamicJson fails to parse an array


Running the following code:

var s = @"{ ""simple"": ""value"", ""obj"": { ""val"":""test"" }, ""array"": []";
var dyn = DynamicJson.Deserialize(s);
Console.WriteLine(dyn.simple);
Console.WriteLine(dyn.obj);
Console.WriteLine(dyn.obj.val);
Console.WriteLine(dyn.array);

Prints:

"value"
{"val":"test"}
base {System.Dynamic.DynamicObject}: {"val":"test"}
"test"
"[]"

Which means dyn.obj returns an object so I can continue to navigate through it but dyn.array returns a string. Meaning I cannot iterate through the list of objects inside.

What am I missing?

EDIT

I think I have found the issue. Looking in github in Pcl.Dynamic.cs method YieldMember does the following:

private bool YieldMember(string name, out object result)
{
    if (_hash.ContainsKey(name))
    {
        var json = _hash[name].ToString();
        if (json.TrimStart(' ').StartsWith("{", StringComparison.Ordinal))
        {
            result = Deserialize(json);
            return true;
        }
        result = json;
        return _hash[name] == result;
    }
    result = null;
    return false;
}

It takes care of converting values starting with { into a deserialized (dynamic) object.

I know @mythz looks at questions in StackOverflow so maybe he can chime in with his thoughts. Seems pretty simple to handle when the json starts with [ right?

EDIT 2

I'm considering this a bug. So I've made the fix in the code and submitted a pull request. In case anyone is curious:

https://github.com/ServiceStack/ServiceStack.Text/pull/442


Solution

  • It was indeed a bug which has been accepted into ServiceStack.Text's source code.

    https://github.com/ServiceStack/ServiceStack.Text/commit/7cd06d3e90bcbfd244af525ed7f584bd4badc31e