【问题标题】:.Net WCF returned string containing JSON appears with \" instead of simple ".Net WCF 返回的包含 JSON 的字符串以 \" 而不是简单的 "
【发布时间】:2018-12-06 19:09:42
【问题描述】:

我正在使用 .NET WCF 服务返回一个字符串,该字符串包含来自我在 MongoDB 中的数据库的 JSON。它运行良好,但是当我执行 GET 时,我得到一个带有 \" 而不是简单的 "

的 Json 文件

例如。我得到\"id\" 而不是"id"

这是我的代码:

string IDeviceService.GetDeviceList()
{
        IMongoCollection<BsonDocument> collection = DatabaseManager.DeviceCollection();
        string deviceList = string.Empty;
        var devices = collection.Find(new BsonDocument()).ToList();

        foreach (var device in devices)
        {
            string json = device.ToString();
            deviceList = (deviceList + json);
        }

        return deviceList;
}

我尝试做一个 .Replace("\\", "") 应该可以解决问题,但它什么也没做。

有什么想法吗?

【问题讨论】:

  • \" 表示报价被转义。因此,如果它在内容中,您应该 将其转义,这样它就不会终止并导致 JSON 格式错误。如果密钥被转义,那么您应该首先查看它是否正确插入到数据库中
  • 关于您的.Replace("\\", "") 不起作用:字符串是不可变的,因此您必须将该方法的结果分配给一个变量。但是,是的,删除转义的反斜杠可能不是一个好主意,具体取决于上下文
  • 如果您发布了您要返回的 json 示例,这将有所帮助。我知道你展示了\"id\",但它确实有助于了解结构中的内容/位置的上下文

标签: c# .net json mongodb wcf


【解决方案1】:

我要返回的 Json:

"{ \"_id\" : ObjectId(\"5b31ee511e7c9ad0bf63b17a\"), \"id\" : \"01\", \"name\" : \"device1\", \"deviceType\" : \"presenceSensor\" }{ \"_id\" : ObjectId(\"5b31ee511e7c9ad0bf63b179\"), \"id\" : \"14\", \"name\" : \"Device14\", \"deviceType\" : \"humiditySensor\" }{ \"_id\" : ObjectId(\"5b31ee511e7c9ad0bf63b17b\"), \"id\" : \"02\", \"name\" : \"device2\", \"deviceType\" : \"humiditySensor\" }{ \"_id\" : ObjectId(\"5b31ee511e7c9ad0bf63b17e\"), \"id\" : \"03\", \"name\" : \"device3.1\", \"deviceType\" : \"temperatureSensor\" }{ \"_id\" : ObjectId(\"5b31f7371e7c9ad0bf63b361\"), \"id\" : \"04\", \"name\" : \"device4\", \"deviceType\" : \"lightSensor\" }"

【讨论】:

    【解决方案2】:

    我想我在这里遇到了类似的问题:Remove escape characters and quoatation marks from JSON

    我也尝试使用 .Replace() 修复它,但我认为您不能使用它来删除转义字符。

    基本上我通过将返回类型更改为 Stream 而不是 string 然后返回 json 字符串来修复它,如下所示:

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return new MemoryStream(Encoding.UTF8.GetBytes(deviceList));
    

    所以不要使用return deviceList;,而是使用上面的行并将string IDeviceService.GetDeviceList()更改为stream IDeviceService.GetDeviceList()

    或者至少类似的东西。您的 WCF 与我的不同,所以可能会有更多内容。

    【讨论】:

    • 我试过了,我要么得到类似{ "__identity": null, "_buffer": [ 123, 32, 34, 95, 105, 100, 34, 32, 58, 32,Unexpected 'O' 的东西
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2015-02-20
    • 2012-11-26
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多