Using JavaScriptConverter for DataContract serialization in C#
I am having problem to find some information about how to get a custom converter invoked for a given property when serializing a C# object to JSON (and vice-versa).
JSON looks like that:
{"ws_status": "success", "result": 32}
or
{"ws_status": "failure", "error_code": 32123}
I have my C# object:
[DataContract]
class WebServiceResult
{
[DataMember(Name = "ws_status", IsRequired = true)]
public Boolean Success { get; private set; }
[DataMember(Name = "error_code")]
public Int32 ErrorCode { get; private set; }
[DataMember(Name = "result")]
public Int32 Result { get; private set; }
}
What I am missing is how to get the JSON values "success" and "failure" converted to a boolean telling me if the WS was successful.
I have implemented a JavaScriptConverter but I don't know how to bind it to my C# object's property.
class JsonStatusConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
g开发者_运维知识库et { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(Boolean) })); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
// Here, do we get a WebServiceResult or directly the WebServiceResult.Success
// object?
Boolean success = obj==null ? false : (Boolean) obj;
Dictionary<string, object> result = new Dictionary<string, object>();
result["ws_status"] = success ? "success" : "error";
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(String))
{
String status = dictionary["ws_status"] as String;
if (status.Equals("success")) return true;
else return false;
}
return null;
}
}
Maybe I misunderstood the concept of JavaScriptConverter and it can only be implemented for the whole WebServiceResult object (which would be a pity because most of the properties are standard).
PS: I know I could simply get the status serialized directly to a string and have a helper method converting that to a boolean in the C# object, but I'd like to learn about converters as I will need them in some other objects.
JsonSerializer/JavaScriptSerializer and DataContractJsonSerializer are distinct entities. DataContractJsonSerializer does not support even the concept of JavaScriptConverters, and JavaScriptSerializer in turn does not honor the DataContract programming model. In addition, with DataContractJsonSerializer, there is no way to do what you want to do here, at all, because boolean is a fundamental primitive in its serialization model, and in its world, extensibility points for primitives are severely curtailed, if not non-existent.
I think your best bet here (sadly) is to ditch this entire model altogether and use Json .NET
精彩评论