[英]c# return json object from string
我有一個數據表,我想將其更改為json。 我是這樣使用json.net lib做到的
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public object LoadTotalCallsPerCampignByRangeFilter(string fromDate, string toDate)
DataTable DTgraph = new DataTable();
....
....
string jsonformatstring = JsonConvert.SerializeObject(DTgraph, Formatting.Indented);
return jsonformatstring;
然后我試圖像這樣從jquery消費它:
$.getJSON('http://localhost:4025/vmp_webservice.asmx/LoadTotalCallsPerCampignByRangeFilter',
{ fromDate: "01-01-2014", toDate: "09-04-2014" } )
.done(function (result) {
alert("hi");
});
我檢查了chrome調試工具(f12),可以看到請求和返回的數據,但是永遠不會觸發警報功能。
這是返回的數據。
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[
{
"Campaign": "default",
"TotalInBound": 216.0
},
{
"Campaign": "direct",
"TotalInBound": 10.0
},
{
"Campaign": "Sales",
"TotalInBound": 151.0
},
{
"Campaign": "Support",
"TotalInBound": 2.0
}
]</string>
我看到了一個問題,在我的Web服務中,它返回的是string formated
而不是json object
那么如何返回對象json而不是字符串格式的json?
謝謝
如果希望將響應顯示為JSON,則需要設置ContentType :
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(jsonformatstring);
HttpContext.Current.Response.End();
嘗試使用完成,始終和失敗方法進行調試。 我的猜測是它試圖將字符串解析為JSON並失敗。 您可以將以下console.log替換為alert
.done(function() {
console.log( "second success" );
})
.fail(function( jqxhr, textStatus, error ) {
console.log( error );
})
.always(function() {
console.log( "complete" );
});
Webservise將返回字符串,因為在將要序列化為字符串並發送給客戶端的return語句之前。
string jsonformatstring = JsonConvert.SerializeObject(DTgraph, Formatting.Indented);
因此,在消耗性應用程序中,您必須反序列化為對象,才能查看對象格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.