【问题标题】:Serialize specific property of object's property/field with JSON.NET使用 JSON.NET 序列化对象属性/字段的特定属性
【发布时间】:2016-08-09 13:43:31
【问题描述】:

假设我有这两个类Book

public class Book
{
    [JsonProperty("author")]
    [---> annotation <---]
    public Person Author { get; }

    [JsonProperty("issueNo")]
    public int IssueNumber { get; }

    [JsonProperty("released")]
    public DateTime ReleaseDate { get; }

   // other properties
}

Person

public class Person
{
    public long Id { get; }

    public string Name { get; }

    public string Country { get; }

   // other properties
}

我想将Book 类序列化为JSON,但不是将属性Author 序列化为整个Person 类我只需要Person 的Name 在JSON 中,所以它应该看起来像这样:

{
    "author": "Charles Dickens",
    "issueNo": 5,
    "released": "15.07.2003T00:00:00",
    // other properties
}

我知道如何实现这一点的两种选择:

  1. Book 类中定义另一个名为 AuthorName 的属性并仅序列化该属性。
  2. 创建自定义JsonConverter,其中仅指定特定属性。

以上两个选项对我来说似乎都是不必要的开销,所以我想问一下是否有任何更简单/更短的方法来指定要序列化的 Person 对象的属性(例如注释)?

提前致谢!

【问题讨论】:

  • 您可以在 getter 中添加另一个 string 类型的属性,返回 Author.Name 并在 setter 中创建 Person(使用给定的名称)。而是序列化该属性(使用JsonProperty("author") 对其进行归因)。
  • 您可以从Person 派生Book 并尝试public string Author { get { return this.Name; } } 可能吗? *编辑:Nvm,无论如何你都不想序列化整个Person 类。为了透明,不删除评论:)
  • @Sinatr 谢谢,我想到了这个选项,但我想避免创建另一个单一用途的属性:P

标签: c# json serialization json.net


【解决方案1】:

序列化string,而不是使用另一个属性序列化Person

public class Book
{
    [JsonIgnore]
    public Person Author { get; private set; } // we need setter to deserialize

    [JsonProperty("author")]
    private string AuthorName // can be private
    {
        get { return Author?.Name; } // null check
        set { Author = new Author { Name = value }; }
    }
}

【讨论】:

  • 为什么要为 AuthorName 提供一个 setter?
  • @oldbam,对于反序列化器:author 值从 json 读取为string,但我们需要Author(另一个属性)值作为Person。这就是AuthorName 的setter 所做的——从string 构造Person 并将其分配给Author 属性。
猜你喜欢
  • 1970-01-01
  • 2015-04-20
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
相关资源
最近更新 更多