Fra*_*r23 11 c# json json.net system.text.json
我想知道JsonPropertySystem.Text.Json 中Newtonsoft.Json/Json.Net字段的等效项是什么。
例子:
using Newtonsoft.Json;
public class Example
{
[JsonProperty("test2")]
public string Test { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
参考:
Fra*_*r23 18
以防万一,其他人会因此而跌倒。该属性被重命名为JsonPropertyName并来自System.Text.Json.Serialization于System.Text.Jsonnuget 包。
例子:
using System.Text.Json.Serialization;
public class Example
{
[JsonPropertyName("test2")]
public string Test { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
参考:
Aar*_*n B 10
请注意,任何发现此问题希望通过System.Text.Json专门获取私有属性来序列化来取代 Newtonsoft 的人。Newtonsoft 会很乐意使用该属性序列化私有属性Newtonsoft.Json.JsonProperty,但添加System.Text.Json.Serialization.JsonPropertyName私有属性不起作用。例如:
enum Animal { Cat, Dog }
class Foo
{
[Newtonsoft.Json.JsonProperty("animals")]
[System.Text.Json.Serialization.JsonPropertyName("animals")]
private string AnimalForSerializer
{
get => AnimalForMe.ToString() + "s";
set => AnimalForMe = Enum.Parse<Animal>(value.TrimEnd('s'));
}
[System.Text.Json.Serialization.JsonIgnore]
[Newtonsoft.Json.JsonIgnore]
public Animal AnimalForMe { get; set; }
}
var b = new Foo { AnimalForMe = Animal.Dog };
var json = System.Text.Json.JsonSerializer.Serialize(b);
var fromJson = System.Text.Json.JsonSerializer.Deserialize<Foo>(json);
Console.WriteLine($"{json} -> {fromJson.AnimalForMe}");
json = Newtonsoft.Json.JsonConvert.SerializeObject(b);
fromJson = Newtonsoft.Json.JsonConvert.DeserializeObject<Foo>(json);
Console.WriteLine($"{json} -> {fromJson.AnimalForMe}");
Run Code Online (Sandbox Code Playgroud)
输出
{} -> Cat
{"animals":"Dogs"} -> Dog
Run Code Online (Sandbox Code Playgroud)
要替换此行为,您需要JsonInclude。或者更确切地说,几乎取代。该System.Text.Json团队决定不支持私有财产。如果您尝试,您将收到类似“‘Foo’类型上的非公共属性‘AnimalForSerializer’用‘JsonIncludeAttribute’注释,这是无效的。”之类的错误。但显然你可以有一个私人设置器:
{} -> Cat
{"animals":"Dogs"} -> Dog
Run Code Online (Sandbox Code Playgroud)
输出
{"animals":"Dogs"} -> Dog
{"animals":"Dogs"} -> Dog
Run Code Online (Sandbox Code Playgroud)
当然,不破坏private封装,但你能做什么呢?