【问题标题】:Is there a way to serialize Json Property name in Newtonsoft?有没有办法在 Newtonsoft 中序列化 Json 属性名称? [关闭]
【发布时间】:2022-01-06 02:05:35
【问题描述】:

我有一个如下所示的类,我想对其进行序列化,使得 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"}

【问题讨论】:

  • 您需要自定义转换器 - Json.Net 不使用 System.Text.Json 属性(反之亦然)。
  • @crimson589 确实可行...但这不是问题所要问的(也许这是 OP 需要的 - 他们绝对可以 edit 澄清问题)
  • @AlexeiLevenkov 很好地基于他的例子,他希望密钥Test 变为tst,这是在我提供的链接中实现的,密钥ReleaseDate 被转换为release_date
  • @crimson589 对我来说(假设 OP 知道他们在说什么)问题是“我的课程通常使用 Text.Json 进行序列化,但由于某种原因我需要使用 Json.Net 但仍然想要获得相同的 JSON 输出”......但实际上,你可能是绝对正确的,并且 OP 正在通过将随机片段复制粘贴在一起来编写代码(粗鲁的假设......应该标记我自己的评论,甚至考虑这种可能性) .

标签: c# api serialization json.net


【解决方案1】:

您必须使用JsonProperty() 属性而不是JsonPropertyName() 属性。您还必须包含 Newtonsoft.Json 而不是 System.Text.Json,这是用于 .NET 的 JSON 库:

using Newtonsoft.Json;
public class TestClass
{
    [JsonProperty(PropertyName ="tst")]
    public string Test{ get; set; }
}

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多