【问题标题】:JSON.Net - Use JsonIgnoreAttribute only on serialization (But not when deserialzing)JSON.Net - 仅在序列化时使用 JsonIgnoreAttribute(但在反序列化时不使用)
【发布时间】:2011-10-06 23:16:27
【问题描述】:

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

我们想要一个所有文档都派生自的基类。基类将具有 DocumentType 属性 - 这本质上是类名。

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

除此之外,当此文档由服务器序列化并发送到客户端时,我们希望将 DocumentType 属性包含在 JSON 中 - 诀窍是我们希望此值是 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 填充它。

【问题讨论】:

  • 你在使用 WCF 吗?还是只是对 ASHX 或 ASPX 的普通旧请求?

标签: c# json.net


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    enum DocumentType {
        XML,
        JSON,
        PDF,
        DOC
    }
    

    在反序列化请求时,如果客户端向您发送无效的枚举,则会给您一个错误。 “InvalidEnumArgumentException”,您可以捕获并告诉客户端它正在发送无效的 DocumentType。

    【讨论】:

    • 看看不同的人如何解释不同的名字很有趣 :) - 这不是 DataType。对我们来说,文档类型类似于“CreateUserDocument”、“UpdateUserDocument”、“UpdateLocationDocument”。我们正在使用 REST,因此我们使用文档来创建/更新/删除和表示资源。
    • 好的,我每天都使用 REST 创建 API,抱歉我不明白你的问题:/.
    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2011-01-21
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多