【问题标题】:return raw JSON string without escape characters返回不带转义字符的原始 JSON 字符串
【发布时间】:2011-11-18 16:43:27
【问题描述】:

我正在查看这篇文章:Returning raw json (string) in wcf。我想我遇到了同样的问题 我有一个返回 JSON 的休息服务,见下面的代码:

IRestServiceImpl.vb

Imports System.ServiceModel
Imports System.ServiceModel.Web

Namespace RestService
' NOTE: You can use the "Rename" command on the context menu to change the interface name "IRestServiceImpl" in both code and config file together.
<ServiceContract()> _
Public Interface IRestServiceImpl
    <OperationContract()> _
    <WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="xml/{id}")> _
    Function XMLData(ByVal id As String) As String


    'WebMessageBodyStyle.Bare WAS WebMessageBodyStyle.wrapped
    <OperationContract()> _
    <WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="api/objects/json/?lat={lat}&lon={lon}&radius={radius}&cat={cat}")> _
    Function JSONData(ByVal lat As String, ByVal lon As String, ByVal radius As String, ByVal cat As String) As String
    'radius in meters


End Interface
End Namespace

RestServiceImpl.vb

Namespace RestService
Public Class RestServiceImpl
    Implements IRestServiceImpl


    Public Function XMLData(ByVal id As String) As String _
        Implements IRestServiceImpl.XMLData

        Return "XML You requested product " & id

    End Function

    Public Function JSONData(ByVal lat As String, ByVal lng As String, ByVal d As String, ByVal cat As String) As String _
        Implements IRestServiceImpl.JSONData

        'returns the results JSON in format

        'Return "JSON lat=" + lat + " lng=" + lng + " d=" + d + " cat=" + cat
        Dim sBuilder As New StringBuilder

        sBuilder.Append("{""hotspots"": [")
        sBuilder.Append("{""id"": ""test_1"",")
        sBuilder.Append("""anchor"": { ""geolocation"": { ""lat"": 52.3729, ""lon"": 4.93 } },  ")
        sBuilder.Append("""text"": {")
        sBuilder.Append("""title"": ""The Layar Office"", ")
        sBuilder.Append("""description"": ""The Location of the Layar Office"", ")
        sBuilder.Append("""footnote"": ""Powered by Layar"" },")
        sBuilder.Append("""imageURL"": ""http:\/\/custom.layar.nl\/layarimage.jpeg"",")
        sBuilder.Append("}")
        sBuilder.Append("],")
        sBuilder.Append("""layer"": ""mytest"",")
        sBuilder.Append("""errorString"": ""ok"", ")
        sBuilder.Append("""errorCode"": 0")
        sBuilder.Append("} ")

        Return sBuilder.ToString

    End Function

End Class
End Namespace

根据上面的代码,我得到了这个响应:

这在 Chrome 浏览器中给了我这个响应: {"JSONDataResult":"{\"热点\": [{\"id\": \"test_1\",\"anchor\": { \"geolocation\": { \"lat\": 52.3729, \ "lon\": 4.93 } }, \"text\": {\"title\": \"The Layar Office\", \"description\": \"The Location of the Layar Office\", \"footnote \": \"Powered by Layar\" },\"imageURL\": \"http:\/\/custom.layar.nl\/layarimage.jpeg\",}],\"layer\": \" mytest\",\"errorString\": \"ok\", \"errorCode\": 0} "}

由于另一个线程中描述的问题(因为我使用 WebMessageFormat.Json),我知道我的回复中有反斜杠。

但我不确定如何实现http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspxhttp://msdn.microsoft.com/en-us/library/ms789010.aspxhttp://msdn.microsoft.com/en-us/library/cc681221(VS.90).aspx 上提供的代码示例

我现在将 Irestserviceimpl.vb 更改为:

Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.IO

Namespace RestService
' NOTE: You can use the "Rename" command on the context menu to change the interface name "IRestServiceImpl" in both code and config file together.
<ServiceContract()> _
Public Interface IRestServiceImpl
    <OperationContract()> _
    <WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="xml/{id}")> _
    Function XMLData(ByVal id As String) As String


    'WebMessageBodyStyle.Bare WAS WebMessageBodyStyle.wrapped
    <OperationContract()> _
    <WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare, UriTemplate:="api/objects/json/?lat={lat}&lon={lon}&radius={radius}&cat={cat}")> _
    Function JSONData(ByVal lat As String, ByVal lon As String, ByVal radius As String, ByVal cat As String) As String
    'radius in meters
End Interface


Public Class RawService
    <OperationContract(), WebGet()> _
    Public Function GetValue() As System.IO.Stream
        Dim result As String = "Hello world"
        Dim resultBytes As Byte() = Encoding.UTF8.GetBytes(result)
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"
        Return New MemoryStream(resultBytes)
    End Function
End Class

End Namespace

但我仍然不确定如何调用 url 或在哪里放置确切的代码...如果有人可以帮助我从这里开始吗?

谢谢!

【问题讨论】:

    标签: asp.net wcf json


    【解决方案1】:

    您的函数正在创建一个巨大的字符串,当它被转换为 Json 时,它正在创建一个 JSON 元素(这是正确的词吗?)只有一个属性“JSONDataResult”,它有一个值 = 您创建的字符串(使用所有这些引号现在都转义了)。

    你做这件事的方式看起来很辛苦! 您是否尝试过使用WCFWebApi? 它很容易实现,并且很容易返回 JSON 或 XML(并为您处理反序列化)

    【讨论】:

    • 我总是愿意接受更好的建议 :) 所以你是说 WCFWebAPI 允许我提供客户端(例如我的 Windows Phone)来调用返回 JSON 的 REST 服务?如果是这样,我现在正在阅读“入门”教程,但我还不清楚。它说我需要创建 ASP.NET MVC 3 应用程序。但是我已经有了一个标准的解决方案,并且在尝试创建新项目时只看到 MVC2 选项。所以: 1. 我怎样才能确保我可以创建 MVC3 项目? 2.如何将功能添加到我现有的(我猜是非 MVC 项目)?谢谢! :)
    • WCFWebApi 不需要 MVC - 我已经将它与 asp.net 表单以及 MVC 甚至 NancyFx 一起运行。只要你设置好路由部分,一切都会好起来的。
    • 我下载了示例应用程序,但出现错误“解决方案中的一个或多个项目未正确加载”。此安装不支持项目类型。所以我尝试将路由部分添加到我的 global.asax 文件中: Public Shared Sub RegisterRoutes(routes As RouteCollection) End Sub 我还将示例应用程序 bin 文件夹中的所有 dll 复制到我自己的 bin 文件夹中。并导入了所有类(C# 中的“使用”)但后来我得到: -Type 'RouteCollection' 未定义 - 在 Imports 'System.Routing' 中指定的命名空间或类型不包含任何公共成员或找不到。
    猜你喜欢
    • 2016-04-13
    • 2020-02-08
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多