Generic WCF JSON Deserialization

davidmdem picture davidmdem · Feb 19, 2010 · Viewed 15.5k times · Source

I am a bit new to WCF and will try to clearly describe what I am trying to do.

I have a WCF webservice that uses JSON requests. I am doing fine sending/receiving JSON for the most part. For example, the following code works well and as expected.

JSON sent:

{ "guy": {"FirstName":"Dave"} }

WCF:

    [DataContract]
    public class SomeGuy
    {
        [DataMember]
        public string FirstName { get; set; }
    }

    [OperationContract]
    [WebInvoke(Method = "POST",
               BodyStyle = WebMessageBodyStyle.WrappedRequest,
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json)]
    public string Register(SomeGuy guy)
    {
        return guy.FirstName;
    }

This returns a JSON object with "Dave" as expected. The problem is that I cannot always guarantee that the JSON I recieve will exactly match the members in my DataContract. For example, the JSON:

{ "guy": {"firstname":"Dave"} }

will not serialize correctly because the case does not match. guy.FirstName will be null. This behavior makes sense, but I don't really know how to get around this. Do I have to force the field names on the client or is there a way I can reconcile on the server side?

A possibly related question: can I accept and serialize a generic JSON object into a StringDictionary or some kind of simple key value structure? So no matter what the field names are sent in the JSON, I can access names and values that have been sent to me? Right now, the only way I can read the data I'm receiving is if it exactly matches a predefined DataContract.

Answer

Juozas Kontvainis picture Juozas Kontvainis · Sep 9, 2011

Here's an alternative way to read json into dictionary:

[DataContract]
public class Contract
    {
    [DataMember]
    public JsonDictionary Registration { get; set; }
    }

[Serializable]
public class JsonDictionary : ISerializable
    {
    private Dictionary<string, object> m_entries;

    public JsonDictionary()
        {
        m_entries = new Dictionary<string, object>();
        }

    public IEnumerable<KeyValuePair<string, object>> Entries
        {
        get { return m_entries; }
        }

    protected JsonDictionary(SerializationInfo info, StreamingContext context)
        {
        m_entries = new Dictionary<string, object>();
        foreach (var entry in info)
            {
            m_entries.Add(entry.Name, entry.Value);
            }
        }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
        foreach (var entry in m_entries)
            {
            info.AddValue(entry.Key, entry.Value);
            }
        }
    }