使用C#的条件JSON序列化 [英] Conditional JSON serialization using C#
问题描述
我有一个类,该类在C#中序列化为JSON并发布到RESTful Web服务.我有一个要求,如果一个字段被填写,则另一个字段将不存在.如果两个字段都序列化到JSON对象中,则服务错误.我的课看起来像这样:
I have a class that I serialize to JSON in C# and post to a RESTful web service. I have a requirment that if one field is filled out another field not be present. The service errors if both fields are serialized into the JSON object. My class looks like this:
[DataContract(Name = "test-object")]
public class TestObject
{
[DataMember(Name = "name")]
public string Name { get; set; }
// If string-value is not null or whitespace do not serialize bool-value
[DataMember(Name = "bool-value")]
public bool BoolValue { get; set; }
// If string-value is null or whitespace do not serialize it
[DataMember(Name = "string-value")]
public string StringValue { get; set; }
}
如注释中所述,如果StringValue具有值,请不要将BoolValue放在JSON对象中.如果StringValue为空,则不要放入StringValue,而要放入BoolValue.
As noted in the comments, if StringValue has a value don't put BoolValue in the JSON object. If StringValue is blank, don't put in StringValue but instead put in BoolValue.
我找到了如何使用XML序列化执行此操作,但是找不到用于JSON序列化的方法.在C#上是否有条件JSON序列化?
I found how to do this with XML serialization, but cannot find a way this works with JSON serialization. Is there conditional JSON serialization on C#?
推荐答案
It appears you are using the DataContractJsonSerializer
. In that case, you can:
- 使用属性
[DataMember(EmitDefaultValue=false)]
可禁止输出空值.
- Disable direct serialization of your properties with the attribute
[IgnoreDataMember]
. - Create proxy
string
andbool?
properties for serialization that return null when they should not be serialized. These can beprivate
. - Set
[DataMember(EmitDefaultValue=false)]
on these proxy properties to suppress output of nulls.
因此:
[DataContract(Name = "test-object")]
public class TestObject
{
[DataMember(Name = "name")]
public string Name { get; set; }
[IgnoreDataMember]
public bool BoolValue { get; set; }
[IgnoreDataMember]
public string StringValue { get; set; }
bool ShouldSerializeStringValue()
{
return !String.IsNullOrWhiteSpace(StringValue);
}
// If string-value is not null or whitespace do not serialize bool-value
[DataMember(Name = "bool-value", EmitDefaultValue=false)]
bool? SerializedBoolValue {
get
{
if (!ShouldSerializeStringValue())
return BoolValue;
return null;
}
set
{
BoolValue = (value ?? false); // Or don't set it at all if value is null - your choice.
}
}
// If string-value is null or whitespace do not serialize it
[DataMember(Name = "string-value", EmitDefaultValue=false)]
string SerializedStringValue {
get
{
if (ShouldSerializeStringValue())
return StringValue;
return null;
}
set
{
StringValue = value;
}
}
}
顺便说一句,这也适用于 Json.NET ,它尊重
Incidentally, this will also work with Json.NET, which respects data contract attributes.
这篇关于使用C#的条件JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!