本文介绍了使用JSON.NET序列化对象的属性/字段的特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这两个类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中,因此它应该看起来像这样:

I want to serialize Book class to JSON, but instead of property Author serialized as whole Person class I only need Person's Name to be in JSON, so it should look like this:

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

我知道如何实现这一目标的两个选择:

I know about two options how to achieve this:

  1. 要在Book类中定义另一个名为AuthorName的属性,并仅序列化该属性.
  2. 在仅指定特定属性的地方创建自定义JsonConverter.
  1. To define another property in Book class called AuthorName and serialize only that property.
  2. To create custom JsonConverter where to specify only specific property.

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

Both options above seem as an unnecessary overhead to me so I would like to ask if there is any easier/shorter way how to specify property of Person object to be serialized (e.g. annotation)?

提前谢谢!

推荐答案

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

Serialize string instead of serializing Person using another property:

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 }; }
    }
}

这篇关于使用JSON.NET序列化对象的属性/字段的特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:41