c# - 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 版有简单的修复方法吗?
解决方案
我运行了以下代码,它适用于 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 信息:
推荐阅读
- android - 使用 Retrofit 进行两次 API 调用以形成一个对象
- python - 从python中的xarray格式获取值
- ios - 如何将编程按钮声明为 var
- ios - 绑定 Objective-C 包时出错
- android - 如何在 RecyclerView 中覆盖项目?
- reactjs - 电子锻造应用程序以空白屏幕启动
- oauth-2.0 - google-oauth2 的最新版本更新了什么?
- intellij-idea - IntelliJ - 如何在所有项目的源代码中查找任何字符?
- pandas - Seaborn 时间序列图
- server - 我无法以我创建的用户身份登录服务器