【问题标题】:How to handle brackets in JSON array sent to Web Service如何处理发送到 Web 服务的 JSON 数组中的括号
【发布时间】: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


【解决方案1】:

您显然在上游配置了一个正在读取请求的处理程序。我想 webmethod 或 scriptmethod 都在添加处理程序,但如果你在一个复杂的项目中,httphandler 可能会起作用。如果不了解您的整个解决方案的更多信息,就不可能找到更好的答案。

如果您只是想自己处理任何原始输入,请构建并注册一个 httphandler。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多