JSON.NET cannot handle simple array deserialization?

北城以北 提交于 2019-12-04 05:43:49

Got the same issue, I used List<T> instead of T[] to fix it.

You are most likely missing a call to ToObject(...) and a type cast. This should work:

class Test { public int Value; }

class Program
{
    static void Main(string[] args)
    {
        var array = new Test[2];
        var instance = new Test {Value = 123};

        array[0] = instance;
        array[1] = instance;

        var settings = new JsonSerializerSettings
        {
            PreserveReferencesHandling = PreserveReferencesHandling.All
        };

        string serialized = JsonConvert.SerializeObject(array, settings);

        // Explicitly call ToObject() and cast to the target type
        var deserialized = (Test[]) ((JArray)JsonConvert.DeserializeObject(serialized, settings)).ToObject(typeof(Test[]));

        Debug.Assert(deserialized[0].Value == 123);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!