Using JavaScriptConverter for DataContract serialization in C#

你。 提交于 2019-12-13 19:07:45

问题


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
    {
        get { 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.


回答1:


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



来源:https://stackoverflow.com/questions/7345487/using-javascriptconverter-for-datacontract-serialization-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!