如何在Json.NET Silverlight中使用TypeNameHandling.Objects反序列化? [英] How can I deserialize with TypeNameHandling.Objects in Json.NET Silverlight?

查看:78
本文介绍了如何在Json.NET Silverlight中使用TypeNameHandling.Objects反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Silverlight中反序列化时出现异常. Test1失败,而Test2成功.我也尝试将TypeNameAssemblyFormat设置为Simple和Full,但是得到相同的结果. Test2可以解析程序集,为什么Json.NET不能?

I get an exception when trying to deserialize in Silverlight. Test1 fails, while Test2 succeeds. I've also tried TypeNameAssemblyFormat to both Simple and Full, but get same results. Test2 can resolve the assembly, why can't Json.NET?

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

Update: Forgot to mention the type I'm trying to deserialize is defined in a different assembly from the silverlight assembly where the deserialization occurs.

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

Both tests work in a non-silverlight .NET application.

如何反序列化具有类型名称的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, Culture=neutral, PublicKeyToken=null"

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

}

推荐答案

尝试将设置添加到JsonConvert.DeserializeObject<T>(json, Settings), 设置为:

Try adding settings to JsonConvert.DeserializeObject<T>(json, Settings), where Settings is:

new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
                }

这篇关于如何在Json.NET Silverlight中使用TypeNameHandling.Objects反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆