您的代码中至少有两个问题。第一个:您将 JSON 序列化两次。第二个:您不能将 JSON 字符串附加到其他数据,因为在结果字符串中不会有更多的 JSON 格式。
如果你为web方法使用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]属性,你返回的对象将自动序列化为JSON字符串。所以你应该不要之前手动序列化它。
如果你想要序列化的对象已经是一个字符串,那么在序列化过程中所有的引号都将被忽略(" 将被替换为\")。在您的情况下,手动对象序列化后,您收到了字符串 [{"__type":"User:#HagarDB", "ID":1}],这是正确的 JSON 字符串。要验证这一点,您只需将字符串粘贴到验证器http://www.jsonlint.com/ 中即可。有关 JSON 格式的更多信息,您可以在 http://www.json.org/ 上阅读。
如果您将数据附加到另一个字符串,例如 "SecurityGroup": 1(这不是 JSON 字符串,正确的是 {"SecurityGroup": 1}),在字符串之间使用逗号,您将收到该字符串
[{"__type":"User:#HagarDB", "ID":1}], "SecurityGroup": 1
这也是错误的 JSON。正确的 JSON 类似于
{ "MyArray": [ {"__type": "User:#HagarDB", "ID": 1 } ], "SecurityGroup": 1 }
最后,您将返回字符串作为 web methid 的结果,并以 {d: result} 的形式接收结果,其中所有配额都将被转义:
{
"d": "[{\"__type\":\"User:#HagarDB\", \"ID\":1}], \"SecurityGroup\": 1"
}
这是一个 JSON 字符串,但不是你想要的。
您的问题的解决方案非常简单。您的网络方法可能如下所示
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyResult MyMethod () {
List<Users> users = BuildMyInnerInformation();
return new MyResult { Users: users, SecurityGroup: 1};
}
public class MyResult {
public List<Users> Users { get; set; }
public int SecurityGroup { get; set; }
}