如何在Json.NET Silverlight中使用TypeNameHandling.Objects进行反序列化?

前端之家收集整理的这篇文章主要介绍了如何在Json.NET Silverlight中使用TypeNameHandling.Objects进行反序列化?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试在Silverlight中反序列化时出现异常. Test1失败,而Test2成功.我也尝试将TypeNameAssemblyFormat同时用于Simple和Full,但得到相同的结果. Test2可以解决程序集,为什么不能Json.NET?

更新:忘记提及我尝试反序列化的类型是在与反序列化发生的silverlight程序集不同的程序集中定义的.

这两个测试都在非Silverlight .NET应用程序中运行.

如何反序列化具有类型名称的json字符串?

private void Test1()
{
    JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.TypeNameHandling = TypeNameHandling.Objects;
    string json1 = "{\"$type\":\"AmberGIS.NetworkTrace.DTO.NTPoint,NetworkTrace.DTO.Assembly\",\"X\":0.0,\"Y\":0.0,\"SpatialReference\":null}";
    try
    {
        var n1 = JsonConvert.DeserializeObject<NTPoint>(json1,settings);
        //Error resolving type specified in JSON 'AmberGIS.NetworkTrace.DTO.NTPoint,NetworkTrace.DTO.Assembly'.
        //Could not load file or assembly 'NetworkTrace.DTO.Assembly,Culture=neutral,PublicKeyToken=null' or one of its dependencies. 
        //The requested assembly version conflicts with what is already bound in the app domain or specified in the manifest. 
        //(Exception from HRESULT: 0x80131053)
    }
    catch (Exception ex)
    {
        while (ex != null)
        {
            Debug.WriteLine(ex.Message);
            ex = ex.InnerException;
        }
    }
}

这个Test2成功了:

private void Test2()
{
    var pnt1 = new AmberGIS.NetworkTrace.DTO.NTPoint();
    Debug.WriteLine(pnt1.GetType().AssemblyQualifiedName);
    // "AmberGIS.NetworkTrace.DTO.NTPoint,NetworkTrace.DTO.Assembly,Version=1.0.0.0,PublicKeyToken=null"

    string fullName = "AmberGIS.NetworkTrace.DTO.NTPoint,PublicKeyToken=null";
    var t = Type.GetType(fullName);
    var pnt2 = Activator.CreateInstance(t) as NTPoint;

}
尝试将设置添加到JsonConvert.DeserializeObject< T>(json,设置),
其中设置为:
new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
                }

猜你在找的Json相关文章