有没有办法在 Newtonsoft 中序列化 Json 属性 名称?
Is there a way to serialize Json Property name in Newtonsoft?
我有一个 class 如下所示,我想对其进行序列化,使 JSON 键成为变量的 JsonPropertyName
,但序列化后的字符串的变量名称为JSON 键。
using System.Text.Json.Serialization
public class TestClass
{
[JsonPropertyName("tst")]
public string Test{ get; set; }
}
序列化器使用 Newtonsoft.Json
var json = JsonConvert.SerializeObject(new TestClass {Test = "some value"})
Console.writeLine(json)
- 实际输出:
{"Test":"some value"}
- 预期输出:
{"tst":"some value"}
有没有办法序列化以属性名字为键的对象
{"tst":"some value"}
您必须使用 JsonProperty()
属性而不是 JsonPropertyName()
属性。您还必须包括 Newtonsoft.Json
而不是 System.Text.Json
,这是用于 .NET 的 JSON 库:
using Newtonsoft.Json;
public class TestClass
{
[JsonProperty(PropertyName ="tst")]
public string Test{ get; set; }
}
我有一个 class 如下所示,我想对其进行序列化,使 JSON 键成为变量的 JsonPropertyName
,但序列化后的字符串的变量名称为JSON 键。
using System.Text.Json.Serialization
public class TestClass
{
[JsonPropertyName("tst")]
public string Test{ get; set; }
}
序列化器使用 Newtonsoft.Json
var json = JsonConvert.SerializeObject(new TestClass {Test = "some value"})
Console.writeLine(json)
- 实际输出:
{"Test":"some value"}
- 预期输出:
{"tst":"some value"}
有没有办法序列化以属性名字为键的对象
{"tst":"some value"}
您必须使用 JsonProperty()
属性而不是 JsonPropertyName()
属性。您还必须包括 Newtonsoft.Json
而不是 System.Text.Json
,这是用于 .NET 的 JSON 库:
using Newtonsoft.Json;
public class TestClass
{
[JsonProperty(PropertyName ="tst")]
public string Test{ get; set; }
}