[英]WCF dynamic json to Dictionary
我正在使用ASPX 4.5。
客戶端發送一個帶有動態字段的JSON對象(每次可以不同)
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");
}
});
}
在服務器端,我試圖將JSON轉換為Dictionary,但出現錯誤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";
}
我究竟做錯了什么?
當您想將原始數據接收到方法參數中時,您必須采用以下方式實現方法:
[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";
}
這樣,您將能夠以在客戶端形成的原始格式接收原始json數據。 然后,您可以按照需要/想要的方式解析它們。
編輯1:
PS不要忘記將UriTemplate =“ form / data”更改為所需的內容。
編輯2:
我認為對於您的情況,最好使用Newtonsoft.Json庫。 它將允許您解析更復雜的數據:
JObject data = JObject.Parse(jsonData);
有兩個問題:
1.我使用@Legart提到的dynamic。
2.參數是一個json對象。
有一個可行的解決方案:
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");
}
});
}
服務器端:
[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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.