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

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

我们想要一个基类,所有文档都将从中派生出来。 基类将具有DocumentType属性 – 这实际上是类名。

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

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

我试图这样做…如果JsonProperty和JsonIgnore属性仅在序列化期间生效而不是反序列化,这将起作用,但遗憾的是情况并非如此。

public abstract class JsonDocument { ///  /// The document type that the concrete class expects to be deserialized from. ///  //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types. public abstract string ExpectedDocumentType { get; } ///  /// The actual document type that was provided in the JSON that the concrete class was deserialized from. ///  [JsonIgnore] // We ignore this property when serializing derived types and instead use the ExpectedDocumentType property. public string DocumentType { get; set; } } 

有谁知道如何实现这一目标?

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

使用ShouldSerialize提供的ShouldSerializefunction。 所以基本上,你的课程看起来像:

 public abstract class JsonDocument { ///  /// The document type that the concrete class expects to be deserialized from. ///  //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types. public abstract string ExpectedDocumentType { get; } ///  /// The actual document type that was provided in the JSON that the concrete class was deserialized from. ///  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 DocumentType { XML, JSON, PDF, DOC } 

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