【问题标题】:Serializing/Deserializing Type properties in Json.net (9.x)Json.net (9.x) 中的序列化/反序列化类型属性
【发布时间】:2018-06-28 00:53:18
【问题描述】:

我有一个类似的对象

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 版有简单的修复方法吗?

【问题讨论】:

  • 您能否添加一行代码,将您的对象转换为 JSON?
  • 为什么要对Type进行序列化
  • 简单的问题是序列化程序将类型更改为字符串,但它无法通过 defaultConverter 反序列化。我过去曾使用此链接来帮助我处理非常相似的情况。 newtonsoft.com/json/help/html/CustomJsonConverter.htm
  • 使用Json.Net 11.0.2版本,无法重现问题。
  • @user2864740 我用的是9.0.1,需要

标签: c# json json.net


【解决方案1】:

我运行了以下代码,它在 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 信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多