.Net WCF返回的包含JSON的字符串以\“而不是简单的”出现

时间:2018-06-27 19:48:58

标签: c# .net json mongodb wcf

我正在使用.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("\\", ""),它应该可以解决问题,但它什么也没做。

有什么主意吗?

2 个答案:

答案 0 :(得分:0)

我要回来的杰森:

"{ \"_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\" }"

答案 1 :(得分:0)

我想我在这里也有类似的问题:Remove escape characters and quoatation marks from JSON

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

基本上,我通过将返回类型更改为Stream而不是字符串,然后像这样返回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与我所在的WCF不同,因此可能还有更多内容。