JSON响应包含额外字符

时间:2016-04-15 15:45:46

标签: json json.net nancy

我使用Nancy创建了一个服务来进行数据库查找并将结果作为JSON返回。这是测试代码:

using (var dt = new DataTable("MyData"))
{
    dt.Columns.Add("id");
    dt.Columns.Add("password");
    dt.Columns.Add("body", System.Type.GetType("System.String"));
    dt.Columns.Add("balance", System.Type.GetType("System.Double"));
    dt.Rows.Add(uid, pwd, "Some useful content", 33.75);
    dt.Rows.Add(uid, pwd, "More useful content", 128.55);
    if (dotNetDataTable)
        json = JsonConvert.SerializeObject(dt, new Serialization.DataTableConverter());
    else
        json = JsonConvert.SerializeObject(dt);
    json = "{\"status\":\"success\",\"data\":" + json + "}";
    return Response.AsJson(json);
}

在返回之前的中断过程,以及json的轮询值,我得到:

"{\"status\":\"success\",\"data\":[{\"id\":\"RMittelman\",\"password\":\"Password\",\"body\":\"Some useful content\",\"balance\":33.75},{\"id\":\"RMittelman\",\"password\":\"Password\",\"body\":\"More useful content\",\"balance\":128.55}]}"

这在即时窗口中似乎是正确的。当我收到数据并中断进程时,我会在客户端即时窗口中看到它:

"\"{\\\"status\\\":\\\"success\\\",\\\"data\\\":[{\\\"id\\\":\\\"RMittelman\\\",\\\"password\\\":\\\"Password\\\",\\\"body\\\":\\\"Some useful content\\\",\\\"balance\\\":33.75},{\\\"id\\\":\\\"RMittelman\\\",\\\"password\\\":\\\"Password\\\",\\\"body\\\":\\\"More useful content\\\",\\\"balance\\\":128.55}]}\""

你可以看到其中包含额外的前导和尾随引号,以及一堆额外的反斜杠。 JSON不会反序列化。以下是客户端文本框中显示的结果:

json result:
"{\"status\":\"success\",\"data\":
[{\"id\":\"RMittelman\",\"password\":\"Password\",\"body\":\"Some useful content\",\"balance\":33.75},
{\"id\":\"RMittelman\",\"password\":\"Password\",\"body\":\"More useful content\",\"balance\":128.55}]}"

Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path '', line 1, position 240.

如果我以编程方式删除前导和尾随引号以及所有反斜杠,它可以正常工作。 以下是我在客户端使用的代码来获取数据:

string GET(string url)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try
    {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            string responseText = reader.ReadToEnd();
            isError = false;
            return responseText;
        }
    }
    catch (WebException ex)
    {
        isError = true;
        WebResponse errorResponse = ex.Response;
        if (errorResponse == null)
            return ex.Message;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            return errorText;
        }
        throw;
    }
}

所以问题是,为什么在发送之前看起来没问题,但在发送后包含所有垃圾?

1 个答案:

答案 0 :(得分:2)

JSON正在进行双重编码。代码是:

json=JsonConvert.SerializeObject(dataTable);

然后

return Response.AsJson(json);

将其更改为:

return (Response)json;

问题消失了。感谢大家的意见!