简体   繁体   中英

Making of JSON Webservice using C# .NET

I am trying to make JSON webservice in C# .NET. A json string is returning by web method but it contains xml structure like:

  <string xmlns="http://tempuri.org/">
  {"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}
  </string> 

I saw this article before it wasn't much helpful for me.

So my problem is, that json string is not returned in its pure format. I do not want that xml version and xmlns string. I plan to consume the web service on Android later.

Can anyone help me?

Thanks

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.

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.

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, ie every result you return get's automatically converted in the Response ContentType you want, ie 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), ie 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM