首页 > 解决方案 > Json.net (9.x) 中的序列化/反序列化类型属性

问题描述

我有一个像

public MyObject
{
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("type")]
    public Type Type { get; set; }
}

我使用序列化设置

new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto,
    TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
};

序列化为

{
    "id": "00000000-0000-0000-0000-000000000000",
    "type": "SomeNamespace.SomeType, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
}

但随后无法反序列化,出现错误

System.ArgumentException

无法从 System.String 转换或转换为 System.Type。

Json.Net 9.0.x 版有简单的修复方法吗?

标签: c#jsonjson.net

解决方案


我运行了以下代码,它适用于 Newtonsoft 9.0.1

private void TestJson()
{
    var jsonSettings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Auto,
        TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
    };

    var myObj = new MyObject
    {
        Type = typeof(string)
    };

    var serialize = JsonConvert.SerializeObject(myObj, jsonSettings);
    var newObj = JsonConvert.DeserializeObject<MyObject>(serialize, jsonSettings);
}

输出:

在此处输入图像描述

DLL 信息:

在此处输入图像描述


推荐阅读