I am trying to make JSON webservice in C# .NET. A json string is returning by web method but it contains xml structure like:
The WCF Web API is worth learning if you plan to create REST services. It's easily installed via Nuget, or from Codeplex
This is also not a problem when using ServiceStack, i.e. every result you return get's automatically converted in the Response ContentType you want, i.e. this is the full code of a simple web service that can be called via all HTTP VERBS (GET,POST,PUT,DELETE) on all the supported formats (no config required), i.e. JSON, XML, HTML, JSV, CSV, SOAP even by a direct HTML Form x-www-form-urlencoded or QueryString request:
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService<Hello> {
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
You can override the response you get with the Accept:application/json HTTP Header or simply adding the ?format=json on the QueryString.
See the ServiceStack's Hello World Example to see a live example the above web services.
Change return in method for
Context.Response.Write(ans);
Context.Response.End();
You can try to build your service using the REST Api. You can find the information on REST with WCF at this link
You can download the toolkit for samples on how to build restful wcf services that returns json response.
If you decorate your interface with attributes for request and response format you can get standard WCF to return and interpret proper json.
[WebGet(UriTemplate = "user/{userid}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
The problem is, however, that WCF's innate DataContractJsonSerializer does not always return proper json. Its serialization of dictionaries is problematic at best, since it is serialized as a list of key/value-pairs. To remedy this one has to return Stream
from the service methods and do the serialization by hand (using Json.NET or ServiceStack to perform the serialization). In such cases it is probably advisable to use WebAPI, but for some cases regular WCF can be used using the mentioned decorations.