小编Isi*_*tar的帖子

构造函数中 C# 记录上的 JsonProperty

使用 C# 9 中的新 C# 记录类型,我想知道是否可以(用于序列化)JsonPropertyAttribute在构造函数参数上设置from Newtonsoft.Json。它似乎不是开箱即用的。

MWE:

using System;
using Newtonsoft.Json;

Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));

record Something([JsonProperty("hello")] string world) {}
Run Code Online (Sandbox Code Playgroud)

输出:

{"world":"something"}
Run Code Online (Sandbox Code Playgroud)

预期输出:

{"hello":"something"}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以让它像这样工作?还是我们必须使用真正的构造函数恢复到属性样式?

internal record Something
{
    public Something(string world) { World = world; }

    [JsonProperty("hello")] public string World { get; }
}
Run Code Online (Sandbox Code Playgroud)

.net c# json.net c#-9.0

4
推荐指数
1
解决办法
934
查看次数

标签 统计

.net ×1

c# ×1

c#-9.0 ×1

json.net ×1