【发布时间】:2017-12-22 19:13:55
【问题描述】:
我有一个 Web 服务,它只捕获入站数据。如果传入的数据是字符串化的 JSON 数组,服务器返回 500 级错误:
ExceptionType : "System.InvalidOperationException"
Message: "Type 'System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array."
at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList)
.........
我做了一些测试,它与字符串化 JSON 数组中的括号有关。发送字符串化的 JSON 对象(只是花括号)不会导致错误。 IE。 "{"id":111,"val":"x"}" 与 "[{"id":111,"val":"x"}]"
让我感到困惑的是,我没有在 web 方法中进行任何反序列化。 在我可以访问请求之前,这一切都发生在上游。网页方法如下:
[WebMethod]
[ScriptMethod]
public void CatchData()
{
HttpRequest inboundRequest = HttpContext.Current.Request;
System.IO.Stream stream = inboundRequest.InputStream;
stream.Position = 0;
string contents = "";
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8))
{
contents = reader.ReadToEnd();
}
}
两个问题:
我需要进行哪些更改以使 Web 方法可以处理字符串化 JSON 中的括号?
这里到底发生了什么?我花了一段时间才意识到 HttpContext.Current.Request.InputStream 正在被 web 方法的上游使用,因此要重新读取其内容,我需要将其位置设置为 0。内容类型时上游发生了什么设置为应用程序/json?如果将内容类型设置为应用程序/文本,则无需重新设置流。
【问题讨论】:
-
听起来你期望的类型是一个数组,但是当数组中只有 1 个对象时,你会触发单个对象。
标签: c# asp.net json web-services asp.net-ajax