JSON.仅在序列化时使用JsonIgnoreAttribute(但在反序列化时不使用)

本文关键字:反序列化 JsonIgnoreAttribute JSON 序列化 | 更新日期: 2023-09-27 18:10:42

我们正在使用JSON.net,并希望使用一致的方式发送和接收数据(文档)。

我们需要一个基类,所有文档都将从它派生。基类将有一个DocumentType属性——这实际上是类名。

当客户端将json序列化的文档发送到服务器时,我们希望对其进行反序列化,并确保客户端指定的DocumentType与服务器上的ExpectedDocumentType匹配。

然后,当这个文档被服务器序列化并发送到客户端时,我们希望JSON中包含DocumentType属性-技巧是我们希望这个值是ExpectedDocumentType的值。

我已经尝试这样做了…如果JsonProperty和JsonIgnore属性只在序列化而不是反序列化期间起作用,那么这将工作,但不幸的是,情况并非如此。

public abstract class JsonDocument
{
    /// <summary>
    /// The document type that the concrete class expects to be deserialized from.
    /// </summary>
    //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
    public abstract string ExpectedDocumentType { get; }

    /// <summary>
    /// The actual document type that was provided in the JSON that the concrete class was deserialized from.
    /// </summary>
    [JsonIgnore] // We ignore this property when serializing derived types and instead use the ExpectedDocumentType property.
    public string DocumentType { get; set; }
}

有人知道如何实现这一点吗?

本质上,逻辑是客户端可以提供任何DocumentType,因此在反序列化期间,服务器需要确保它与ExpectedDocumentType匹配,然后在序列化期间,当服务器将此文档发送给客户端时,服务器知道正确的DocumentType,因此需要用ExpectedDocumentType填充它。

JSON.仅在序列化时使用JsonIgnoreAttribute(但在反序列化时不使用)

使用Json.Net提供的ShouldSerialize特性。基本上,你的类看起来像:

public abstract class JsonDocument
{
    /// <summary>
    /// The document type that the concrete class expects to be deserialized from.
    /// </summary>
    //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
    public abstract string ExpectedDocumentType { get; }
    /// <summary>
    /// The actual document type that was provided in the JSON that the concrete class was deserialized from.
    /// </summary>
    public string DocumentType { get; set; }
    //Tells json.net to not serialize DocumentType, but allows DocumentType to be deserialized
    public bool ShouldSerializeDocumentType()
    {
        return false;
    }
}

你可以用一个Enum来做这个,我不知道DocumentType是否是一个Enum,但它应该。

enum DocumentType {
    XML,
    JSON,
    PDF,
    DOC
}

当反序列化请求时,如果客户端发送给你一个无效的enum,它将给你一个错误。"InvalidEnumArgumentException",你可以捕捉并告诉客户端它正在发送一个无效的DocumentType