我的示例代码很简单:
using System.Text.Json.Serialization;
using Newtonsoft.Json;
public class C {
public C(string PracticeName) { this.PracticeName = PracticeName; }
public string PracticeName;
}
var x = new C("1");
var json = JsonConvert.SerializeObject(x); // returns "{"PracticeName":"1"}"
var x1 = JsonConvert.DeserializeObject<C>(json); // correctly builds a C
var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C>(json);
最后一行提出:
抛出异常:System.Text.Json.dll 中的System.NullReferenceException"对象引用未设置为对象的实例.
Exception thrown: 'System.NullReferenceException' in System.Text.Json.dll Object reference not set to an instance of an object.
我做错了什么?
(请注意,这是最新的 .NET Core 3 预览版 5 和最新的 System.Text.Json 4.6.0-preview6.19259.10)
(Note this is on latest .NET Core 3 preview 5 with latest System.Text.Json 4.6.0-preview6.19259.10)
添加无参数构造函数可以防止异常,但是我不想要/不需要无参数构造函数,没有它,Json.Net 解析得很好.
Adding a parameterless constructor prevents the exception however I don't want/need a parameterless constructor and Json.Net parses fine without it.
有没有办法让 System.Text.Json 像 Json.Net 一样使用给定的构造函数进行解析?
Is there a way to make System.Text.Json parse using the given constructor like Json.Net does ?
目前,.NET Core 3.0 支持 JSON 还没有完成,貌似只支持无参构造函数.将来可能会添加该功能.
In it's current state, JSON Support in .NET Core 3.0 is still not finished, and it seems only a parameterless constructor is supported. It might be, that that feature will be added in future.
当您想使用 .net 框架中的新 Json API 时,一个 解决方法 选项是为您的序列化模型创建一个无参数构造函数.可能我们根本不应该对普通的数据传输对象使用构造函数,因此我认为它是一种选择,而不是一种解决方法.
One workaround option would be to make a parameterless constructor for your serialized model, when you want to use the new Json API from the .net framework. Probably we shouldn't use constructors for plain datatransfer objects at all, hence I see it as option, not as a workaround.
如果您寻找一种方法,关于如何从旧版本迁移到 .net core 3.0,或者无论如何使用 Newtonsoft.Json
,这已记录在 这里:
If you search for a way, on how to migrate from an older version to .net core 3.0, or use Newtonsoft.Json
anyway, this is documented here:
MVC:
安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson
打包,并将其注册到您的服务:
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson
package, and register it to your services:
services.AddMvc().AddNewtonsoftJson();
SignalR:
安装 Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson
包
//Client
new HubConnectionBuilder()
.WithUrl("/chatHub")
.AddNewtonsoftJsonProtocol(...)
.Build();
//Server
services.AddSignalR().AddNewtonsoftJsonProtocol(...);
这样你应该*能够在 .Net Core 3.0 中使用 Json.NET 功能
That way you should* be able to use Json.NET Features in .Net Core 3.0
*我没有安装,所以无法测试
这篇关于使用 System.Text.Json.Serialization 解析 json 的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!