Exception parsing json with System.Text.Json.Serialization

笑着哭i 提交于 2019-12-06 13:23:56

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.

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.

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:

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

services.AddMvc().AddNewtonsoftJson();

SignalR:

Install Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson package

//Client
new HubConnectionBuilder()
.WithUrl("/chatHub")
.AddNewtonsoftJsonProtocol(...)
.Build();

//Server
services.AddSignalR().AddNewtonsoftJsonProtocol(...);

That way you should* be able to use Json.NET Features in .Net Core 3.0

*I don't have installed it, so I can not test it

PracticeName needs to be a property, not a field. Try that w/ the parameterless constructor.

I developed a quick console program class. The class C1 is converted via the Newtonsoft.Json package. The class C2 is parsed via the System.Text.Json package.

using Newtonsoft.Json;

namespace TestJsonParse
{
    class Program
    {
        static void Main(string[] args)
        {
            var c1 = new C1("1");
            var json1 = JsonConvert.SerializeObject(c1); // returns "{\"PracticeName\":\"1\"}"
            var x1 = JsonConvert.DeserializeObject<C1>(json1); // correctly builds a C1

            var c2 = new C2();
            string json2 = "{\"PracticeName\":\"1\"}";
            var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C2>(json2); // correctly builds a C2
        }

        class C1
        {
            public C1(string PracticeName) { this.PracticeName = PracticeName; }
            public string PracticeName;
        }

        class C2
        {
            public C2() { }
            public string PracticeName { get; set; }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!