[英]C# WebService return json
我需要從此Web服務返回以下消息,但它必須為json格式。 現在有可能實現這一目標嗎?
C#代碼:
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代碼:
//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",
});
});
響應:
<?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>
followig語句返回一個json響應
string json = JavaScriptSerializer.Serialize({"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"});
return json;
使用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;
}
您必須使用Newtonsoft.Json;
public string HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
var jsondata = JsonConvert.SerializeObject(obj);
return jsondata.ToString();
}
正確的C#代碼:
public String HelloWorld()
{
response obj = new response
{
message = "No fromFormat recieved.",
success = false
};
return new JavaScriptSerializer().Serialize(obj);
}
正確的jQuery代碼是:
$('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",
});
});
響應:
{“ message”:“否收到fromFormat。”,“成功”:false}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.