问题
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; }
}
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.
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#?
回答1:
It appears you are using the DataContractJsonSerializer. In that case, you can:
- 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.
Thus:
[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;
}
}
}
Incidentally, this will also work with Json.NET, which respects data contract attributes.
来源:https://stackoverflow.com/questions/29173381/conditional-json-serialization-using-c-sharp