1

I'm building a Web Service in VB.NET and I want to answer using JSON. Currently my answers looks like this

{\"myVar1\" : \"From moscow\", \"myVar2\" : \"With love\"}

I would like to be able to use " (and CarriageReturn), and have the reponse like this :

{"myVar1" : "From moscow", "myVar2" : "With love"}

How can I avoid this transcoding of the " in \" ?

Here is my interface definition :

<OperationContract()>
<WebGet(UriTemplate:="/TemplateGet?ID={id}",
        ResponseFormat:=WebMessageFormat.Json, 
        BodyStyle:=WebMessageBodyStyle.Bare)>
Function TemplateGet(id As String) As String

My answer is plain String :

Function TemplateGet(id As String) As String Implements ISearch.TemplateGet
    Dim reponse As String = "{""MyVar1"" : ""From moscow"", ""MyVar2"" : ""With love""}"
    Return reponse
End Function
Rabskatran
  • 2,269
  • 5
  • 27
  • 41

1 Answers1

1

I am not a VB.net guy, (and i didn't find a vb example) so the link will use c# - but with a simple translation to vb it should be the same.

When you write a wcf service, you shouldn't write the serialization (to json in your case) by yourself.

you can return an object (which you should register as a known type - see the example below) and the result will be serialized for you.

example for a wcf service with objects: http://www.freddes.se/2010/05/19/wcf-knowntype-attribute-example/

in your case you should create a class like that:

   [DataContract]
   public class MyServiceResultClass
   {
       [DataMember]
       public string myVar1 {get; set;}

       [DataMember]
       public string myVar2 {get; set;}
   }

register MyServiceResultClass as a service known type, and change your method to something like that:

   Function TemplateGet(id As String) As String Implements ISearch.TemplateGet
      Dim reponse As MyServiceResultClass = new MyServiceResultClass() // -- Change to vb syntax here
      Return reponse
   End Function

and thats it... you will get the response in json

eyossi
  • 4,230
  • 22
  • 20