3

My service method:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getDataFromTrainingMaster()
{
    List<TrainingMasterDataStruct> results = new DAL().GetDataFromTrainingMaster();
    JavaScriptSerializer js = new JavaScriptSerializer();                    
    return js.Serialize(results).ToString(); 
}

My .net web service returns JSON wrapped in XML as follows:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">   [{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}]

I need it in the following format:

"Training":[{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}]</string>

How can I do this?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
bapi
  • 1,903
  • 10
  • 34
  • 59
  • What technology have you used to create the web service? ASP.NET Web API? Static page method? WCF? – Snixtor Feb 19 '13 at 05:45
  • Thanks for clarifying by adding your server-side code, I see you're using `WebMethod` attribute. This is one of *many* different web service frameworks, so be sure to mention that when raising a question. Looks like the same issue discussed (and answered) here - http://stackoverflow.com/questions/5611134/responseformat-json-returns-xml – Snixtor Feb 19 '13 at 08:24

5 Answers5

2

There's no need to create the JSON string yourself. Return the List<TrainingMasterDataStruct> and let .NET serialise it for you on the fly:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<TrainingMasterDataStruct> getDataFromTrainingMaster()
{
   List<TrainingMasterDataStruct> list = doStuff();
   return list;
}

Secondly, the non-static method signatures suggest this is an asmx file (page methods are static). By default these serialise to xml so you will need to uncomment or add the System.Web.Script.Services.ScriptService attribute to the web service class:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

This allows it to return JSON. One issue: The JSON serialiser seems to be able to serialise more types than XML so be careful here if you want to output either/or - use Lists and arrays here rather than collections.

Thirdly and very importantly, the CLIENT must indicate to the server that it desires a JSON response.

To test and verify this third point, I suggest you follow the above steps and then make a call to the web service from a test web page using jQuery and monitor the traffic in Fiddler. Something like:

$.ajax({
        type: "POST",
        url: "WebService.asmx/getDataFromTrainingMaster",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "",
        success: function (msg) { }
    });

This is what a JSON request/response looks like - pay particular attention to the POST, Accept and Content-Type headers:

POST http://scrubbed/GetVehicles HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-gb
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)
Host: scrubbed
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Mon, 04 Oct 2010 10:49:12 GMT
Content-Length: 1417

{"d":{"Data":[{"Key":1,"Value":[{"VehicleId":15036,"VehicleAlias":"Whatever","Expiry":"\/Date(1915983035043)\/","Expired":false},{"VehicleId":
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
0

Try changing your return type to List<TrainingMasterDataStruct> and returning "results". You don't need to serialize the string yourself, ASP.NET with the WebMethod attribute will take care of that for you.

Neha
  • 2,933
  • 3
  • 19
  • 23
0

You can try this:

var data = [{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}]

var result = JSON.stringify({ Training: data })

result will give you the desired output.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Ni3
  • 489
  • 3
  • 12
  • from which namespace "JSON" belogs.Now getting error, "JSON" is not in current context. – bapi Feb 19 '13 at 09:52
  • Actually json.stringify is a javascript function so you can try using ajax to call your web service on client side and use this.May be this will work. – Ni3 Feb 19 '13 at 10:34
  • JSON.stringify is not built in to all browsers. Use json2.js. https://github.com/douglascrockford/JSON-js – Stephen Kennedy May 29 '13 at 13:44
0

I had a similar error. One method returns the response in correct json format but another method returns xml in the same asmx.

Here the two methods:

Response in JSON format:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string loginOne(string param1, string param2){
          result = new JObject();
          ...
          ...
          return result.ToString();
    }

Response in XML format:

 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getCompaniesOne()
    {
        ...
        ...
        return result.ToString();
    }

How I solved?

Adding a dummy parameter to the wrong response method.

 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getCompaniesOne(string dummy)
    {
       ...
       ...
       return result.ToString();
    }       

I Hope this help.

0

The problem can be circumvented in the following way.

This asmx service will return the JSON value: {"d":"Hello World"}

<%@ WebService Language="C#" CodeBehind="Data.asmx.cs" Class="WebServiceData" %>

using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebServiceData : WebService
{
    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void Get()
    {
        object ret = new {
            d = "Hello World"
        };

        string retjson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ret);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.AddHeader("content-length", retjson.Length.ToString());
        HttpContext.Current.Response.Write(retjson);
        HttpContext.Current.Response.Flush();
    }
}
Dmitry Shashurov
  • 1,148
  • 13
  • 11