1

I was checking this post: Returning raw json (string) in wcf. I think Im running into somewhat the same problem I have a rest service that returnS JSON, see the code below:

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

Based on the above code I get this response:

Which gives me this response in Chrome browser: {"JSONDataResult":"{\"hotspots\": [{\"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} "}

I know think the backslashes are in my response because of the issue described in the other thread (since Im using WebMessageFormat.Json).

But Im unsure how to implement the code samples that were provided on http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx, http://msdn.microsoft.com/en-us/library/ms789010.aspx and http://msdn.microsoft.com/en-us/library/cc681221(VS.90).aspx

I now changed my Irestserviceimpl.vb to:

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

But am still unsure how to call the url or where to place which code exactly...if anyone could help me get started here?

Thanks!

Community
  • 1
  • 1
Adam
  • 6,041
  • 36
  • 120
  • 208

1 Answers1

1

Your function is creating one massive string, which when it gets converted to Json is creating a JSON element(is that the right word?) with only one attribute "JSONDataResult" which has a single value = the string you made (with all those quote marks now escaped).

The way you are doing it looks like quite hard work! Have you tried using the WCFWebApi? It's easy to implement and makes it very easy to return JSON or XML (and handles the de-serialization for you)

Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
  • Im always open to better suggestions :) So you're saying that WCFWebAPI allows me to offer clients (such as my Windows Phone) to call a REST service that returns JSON? If so, I'm now reading the "getting started" tutorial, but its not clear to me yet. It says I need to create ASP.NET MVC 3 application. But I already have a standard solution and only see MVC2 option when trying to create a new project. so: 1. How can I make sure I can create MVC3 projects? 2. How can I add the functionality to my existing (I guess non-MVC project)? Thanks! :) – Adam Nov 18 '11 at 20:27
  • The WCFWebApi doesn't *need* MVC - I have run it alongside asp.net forms as well as MVC and even NancyFx. As long as you set up the routing part all will be well. – Neil Thompson Nov 19 '11 at 12:16
  • I downloaded the sample app but that gives me error 'one or more projects in the solution were not loaded correctly'. The project type is not supported by this installation. So I tried adding the routing part to my global.asax file: Public Shared Sub RegisterRoutes(routes As RouteCollection) End Sub I also copied all dlls from the sample app bin folder to my own bin folder. And imported all classes('using' in C#') But then I get: -Type 'RouteCollection' is not defined -Namespace or type specified in the Imports 'System.Routing' doesn't contain any public member or cannot be found. – Adam Nov 19 '11 at 14:53