使用System.Text.Json.Serialization解析json的异常 [英] Exception parsing json with System.Text.Json.Serialization

查看:255
本文介绍了使用System.Text.Json.Serialization解析json的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例代码非常简单:

My sample code is very simple:

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.

我在做什么错了?

(请注意,这是在具有最新System.Text.Json 4.6.0-preview6.19259.10的最新.NET Core 3预览5上)

(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.

是否有一种方法可以像Json.Net一样使用给定的构造函数来解析System.Text.Json?

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:

安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 软件包,并将其注册到您的服务中:

Install Microsoft.AspNetCore.Mvc.NewtonsoftJson package, and register it to your services:

services.AddMvc().AddNewtonsoftJson();

安装 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的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆