kof*_*fus 2 c# json.net .net-core .net-core-3.0 system.text.json
我的示例代码非常简单:
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);
Run Code Online (Sandbox Code Playgroud)
最后一行引发:
引发异常:System.Text.Json.dll中的“ System.NullReferenceException”对象引用未设置为对象的实例。
我究竟做错了什么 ?
(Note this is on latest .NET Core 3 preview 5 with latest System.Text.Json 4.6.0-preview6.19259.10)
Adding a parameterless constructor prevents the exception however I don't want/need a parameterless constructor and Json.Net parses fine without it.
Is there a way to make System.Text.Json parse using the given constructor like Json.Net does ?
在当前状态下,.NET Core 3.0中的JSON支持仍未完成,并且似乎仅支持无参数构造函数。将来可能会添加该功能。
一种解决方法是,当您要使用.net框架中的新Json API时,为序列化模型创建无参数构造函数。可能我们根本不应该为纯数据传输对象使用构造函数,因此我将其视为选项,而不是解决方法。
如果您寻找一种方法,有关如何从较早版本迁移到.net core 3.0或Newtonsoft.Json仍要使用的方法,请参见此处:
MVC:
安装Microsoft.AspNetCore.Mvc.NewtonsoftJson软件包,并将其注册到您的服务中:
services.AddMvc().AddNewtonsoftJson();
Run Code Online (Sandbox Code Playgroud)
安装Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson套件
//Client
new HubConnectionBuilder()
.WithUrl("/chatHub")
.AddNewtonsoftJsonProtocol(...)
.Build();
//Server
services.AddSignalR().AddNewtonsoftJsonProtocol(...);
Run Code Online (Sandbox Code Playgroud)
这样,您应该*能够在.Net Core 3.0中使用Json.NET功能
*我尚未安装,因此无法测试
| 归档时间: |
|
| 查看次数: |
3367 次 |
| 最近记录: |