Yaroslav
Yaroslav

Reputation: 155

Pretty formatted json response with WCF

I'm using WCF RESTfull service which responds in JSON format, but by default WCF service sends not pretty formatted JSON messages (i mean json object without tabulation).

By default WCF sends JSON like that:

{"ResponseBody":{"Code":"0011","InvocationTime":278,"Message":""},"ResponseInformation":{"ServiceCode":0,"ServiceMessage":"Successfull","ServiceInvocationTime":0}}

But i need this:

{
"ResponseBody": {
    "Code": "0011",
    "InvocationTime": 278,
    "Message": ""
},
"ResponseInformation": {
    "ServiceCode": 0,
    "ServiceMessage": "Successfull",
    "ServiceInvocationTime": 0
}

Does anybody knows solution of this simple problem? Thanks!

Upvotes: 3

Views: 446

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32561

You may use Json.NET. Add a reference to the library (also available as a NuGet package) and add

using Newtonsoft.Json;

to your class file. Then, do the following:

var json = "{\"ResponseBody\":{\"Code\":\"0011\",\"InvocationTime\":278,\"Message\":\"\"},\"ResponseInformation\":{\"ServiceCode\":0,\"ServiceMessage\":\"Successfull\",\"ServiceInvocationTime\":0}}";
var formattedJson = JsonConvert.DeserializeObject(json).ToString();

Upvotes: 2

nichu09
nichu09

Reputation: 892

normally wcf responds in xml format .so if you specify that response in json, it will give the result in jason format.below example the request in xml format and response in json format.

 [OperationContract]
    [WebInvoke(Method = "GET",
        RequestFormat = WebMessageFormat.Xml,
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare,
       UriTemplate = "GetAllcustomer")]
   List< CustomerResponse> GetAllCustomerDetails();

Upvotes: 0

Related Questions