简体   繁体   中英

WCF dynamic json to Dictionary

I'm using ASPX 4.5.
The client sends one JSON object with dynamic fields (can be different each time)

function storeDataInSession(formData) {
    var data = {};
    data["formData"] = formData;

    $.ajax({
        url: "MY_URL/StoreFormData",
        type: "post",
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'json',
        success: function (data, textStatus, xhr) {
            console.log(data);
            console.log("success");
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log("failure");
        }
    });
}

On the server side I'm trying to convert that JSON to Dictionary, but I'm getting error 500.

[OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public String StoreFormData(dynamic formData) 
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Dictionary<string, string> formValues = jss.Deserialize<Dictionary<string, string>>(formData);


        return "aaaaa";
    }

What am I doing wrong?

As you want to receive raw data into your method param, you have to implement your method in a way:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "form/data",
    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public String StoreFormData(Stream fileContents)
{
    using (StreamReader reader = new StreamReader(fileContents))
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();

        //here is your json, received from a client
        string jsonData = reader.ReadToEnd();

        // I think for that you case it's better to use Newtonsoft.Json library. It will allow you to parse more complex data
        //JObject data = JObject.Parse(jsonData); 

        //Dictionary<string, string> formValues = jss.Deserialize<Dictionary<string, string>>(formData);
    }

    return "aaaaa";
}

In such a way you will be able to receive plain json data in the way it was formed on a client side. Then you can parse them in a way you need/want.

EDIT 1:

PS Don't forget to change UriTemplate = "form/data" to whatever you need.

EDIT 2:

I think that for your case it's better to use Newtonsoft.Json library. It will allow you to parse more complex data:

JObject data = JObject.Parse(jsonData); 

There were 2 problems:
1. I used dynamic as @Legart mentioned.
2. The parameter was a json object.

There are a working solution:

function storeDataInSession(formData) {
    var data = {};
    data["formData"] = JSON.stringify(formData);

    $.ajax({
        url: "MYURL/StoreFormData",
        type: "post",
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'json',
        success: function (data, textStatus, xhr) {
            console.log(data);
            console.log("success");
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log("failure");
        }
    });
}

The server side:

[OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public String StoreFormData(string formData) 
    {        
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Dictionary<string, string> formValues = jss.Deserialize<Dictionary<string, string>>(formData);

        string test = "test:  ";
        foreach (KeyValuePair<string, string> item in formValues) 
        {
            test += String.Format(" key: {0}  value: {1} ", item.Key, item.Value);
        }



        return formData;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM