sbje098 2017-07-10 10:51 采纳率: 0%
浏览 1491

关于Ajax Post Json数据到Webservice

客户端代码:
function LoadData4() {
$.ajax({
type: "POST",
url: "http://localhost:6698/WebServiceTestJson2.asmx/TestJson2",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{'students': [{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]}",
success: function (json) { alert(json.d) },
error: function (error) {
alert("调用出错" + error.responseText);
}
});
}
Webservice代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string TestJson2(string students)
{
WriteLog(students);
try
{
if (students == null || students == "")
return "No data";
JavaScriptSerializer js = new JavaScriptSerializer();
List list = js.Deserialize>(students);
string test = "";
string other = "";
for (int i = 0; i < list.Count; i++)
{
test = test + list[i].Name;
other = other + list[i].other.other1;
}
return test + "\" + other;
}
catch (Exception e)
{
return e.ToString();
}
}

    public class Student
    {
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Age { get; set; }
        public string Address { get; set; }
        public Other other { get; set; }

    }

             public class Other
    {
        public string other1 { get; set; }
        public string other2 { get; set; }
    }

当我在客户端调用的时候报错:
Type \u0027System.String\u0027 is not supported for deserialization of an array!

但是我在Webservce上直接用下面的Json字符串用Invoke调用是没有任何问题。
[{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]

请教各位大神,是什么原因导致客户端调用出错?谢谢!

  • 写回答

3条回答 默认 最新

  • Go 旅城通票 2017-07-11 01:50
    关注

    自己比较2个字符不就知道了,ajax传递的是JSON对象,不是JSON对象数组,你要序列化的为对象数组,肯定不行了

    data: "{'students': [{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]}",

    ===>去掉{'students': 和最后的},传递json对象数组,而不是json对象

    data: "[{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]",

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog