Conditional JSON serialization using C# -
i have class serialize json in c# , post restful web service. have requirment if 1 field filled out field not present. service errors if both fields serialized json object. class looks this:
[datacontract(name = "test-object")] public class testobject { [datamember(name = "name")] public string name { get; set; } // if string-value not null or whitespace not serialize bool-value [datamember(name = "bool-value")] public bool boolvalue { get; set; } // if string-value null or whitespace not serialize [datamember(name = "string-value")] public string stringvalue { get; set; } }
as noted in comments, if stringvalue has value don't put boolvalue in json object. if stringvalue blank, don't put in stringvalue instead put in boolvalue.
i found how xml serialization, cannot find way works json serialization. there conditional json serialization on c#?
it appears using datacontractjsonserializer
. in case, can:
- disable direct serialization of properties attribute
[ignoredatamember]
. - create proxy
string
,bool?
properties serialization return null when should not serialized. these canprivate
. - set
[datamember(emitdefaultvalue=false)]
on these proxy properties 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 not null or whitespace not serialize bool-value [datamember(name = "bool-value", emitdefaultvalue=false)] bool? serializedboolvalue { { if (!shouldserializestringvalue()) return boolvalue; return null; } set { boolvalue = (value ?? false); // or don't set @ if value null - choice. } } // if string-value null or whitespace not serialize [datamember(name = "string-value", emitdefaultvalue=false)] string serializedstringvalue { { if (shouldserializestringvalue()) return stringvalue; return null; } set { stringvalue = value; } } }
incidentally, work json.net, respects data contract attributes.
Comments
Post a Comment