Generic WCF JSON Deserialization

后端 未结 5 1196
野的像风
野的像风 2020-12-05 11:33

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 JS

5条回答
  •  眼角桃花
    2020-12-05 12:18

    In order to achieve my goal of having a service that can accept a completely arbitrary list of "key": "value" pairs as a raw JSON string and then decide what do do with them without having to know the "key" names beforehand, I combined casper and aaron's advice.

    1st, to access the raw JSON string, this MSDN blog was very helpful.

    I was unable to simply change the single method parameter to String and the BodyStyle to WebMessageBodyStyle.Bare without problems. When setting BodyStyle to Bare, make sure that the endpoint behaviorConfiguration is set to and not .

    The second note is that, as casperOne mentioned, the method can only have 1 parameter. This parameter needs to be a Stream in order to access the raw text though (see MSDN blog above).

    Once you have the raw JSON string, it's just a matter of deserializing it into a StringDictionary. I chose JSON.Net for this and it works wonderfully. Here's a bare bones example to illustrate.

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json)]
    public string Register(Stream rawJSON)
    { 
        // Convert our raw JSON string into a key, value
        StreamReader sr = new StreamReader(rawJSON);
        Dictionary registration =     
            JsonConvert.DeserializeObject>(
                sr.ReadToEnd());
    
        // Loop through the fields we've been sent.
        foreach (KeyValuePair pair in registration)
        {
            switch (pair.Key.ToLower())
            {
                case "firstname":
                    return pair.Value;
                    break;
            }
    
        }
    }
    

    This allows me to accept an arbitrary list of fields via JSON and for the field names to be case insensitive. I know it's not the strictest approach to data integrity or to how WCF services would ideally be structured, but, as far as I can tell, it's the simplest way to get where I want to go.

提交回复
热议问题