Reputation: 11824
I need to return a message from this web service bellow, but it has to be in json format. Is it possible to achieve this now?
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
namespace WebApplication1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public response HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
return obj;
}
}
public class response
{
public string message = "";
public Boolean success = false;
}
}
jQuery code:
//contentType: "application/json" if I add this line, response is undefined.
$('document').ready(function () {
$.ajax({
url: 'http://exampleUrl.com/WebService1.asmx/HelloWorld',
type: 'POST',
success: function (data) {
console.log(data.responseText);
},
error: function (data) {
console.log(data.responseText);
},
async: false,
dataType: "json",
});
});
Response:
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<message>No fromFormat recieved.</message>
<success>false</success>
</response>
Upvotes: 0
Views: 1992
Reputation: 11824
Correct C# code:
public String HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
return new JavaScriptSerializer().Serialize(obj);
}
Correct jQuery code is:
$('document').ready(function () {
$.ajax({
url: 'http://exampleUrl.com/WebService1.asmx/HelloWorld',
type: 'POST',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
async: false,
dataType: "json",
});
});
Response:
{"message":"No fromFormat recieved.","success":false}
Upvotes: 0
Reputation: 5474
use Newtonsoft.Json http://james.newtonking.com/json/help/index.html?topic=html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm
public response HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
string Result = JsonConvert.SerializeObject(obj);
return obj;
}
Upvotes: 1
Reputation: 221
The followig statement returns a json response
string json = JavaScriptSerializer.Serialize({"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"});
return json;
Upvotes: 1
Reputation: 7601
You have to use Newtonsoft.Json;
public string HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
var jsondata = JsonConvert.SerializeObject(obj);
return jsondata.ToString();
}
Upvotes: 0