[英]How to send back JSON in asp.net?
說我會在PHP中有這個:
<?php
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
));
?>
我怎樣才能在asp .net中獲得等價物?
就像用戶去了giveMeJson.aspx
我希望它返回與giveMeSomeJson.php
相同。
謝謝
在一個空的.aspx(使用Json.Net)后面的代碼中:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class giveMeSomeJson : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
Response.ContentType = "text/json";
var year = DateTime.Now.Year;
var month = DateTime.Now.Month;
Response.Write(JsonConvert.SerializeObject(new[]
{
new
{
id = "111",
title = "Event1",
start = String.Format("{0}-{1}-10", year, month),
url = "http://yahoo.com/"
},
new
{
id = "222",
title = "Event2",
start = String.Format("{0}-{1}-20", year, month),
url = "http://yahoo.com/"
}
}));
}
}
}
或者,只需使用.aspx中的代碼:
<%@ Page Language="C#" %>
<%@ Import Namespace="Newtonsoft.Json" %>
<script runat="server">
string json = JsonConvert.SerializeObject(new[]
{
new
{
id = "111",
title = "Event1",
start = String.Format("{0}-{1}-10", DateTime.Now.Year, DateTime.Now.Month),
url = "http://yahoo.com/"
},
new
{
id = "222",
title = "Event2",
start = String.Format("{0}-{1}-20", DateTime.Now.Year, DateTime.Now.Month),
url = "http://yahoo.com/"
}
});
</script>
<%= json %>
如果沒有進入ASP.NET中的輸出的各種寫入方式(有很多),您可以使用JavaScriptSerializer
或JSON.NET將.NET數組序列化為JSON,然后將其寫入輸出。
使用JSON.NET,它是:
Person[] arr = new[] { new Person { Name = "John" }, new Person { Name = "Jane" } };
string json = JsonConvert.SerializeObject(arr);
現在可以將json
字符串寫入響應。 您可以使用Literal
控件或<%= %>
語法,或直接寫入響應對象等。
編輯 :
最簡單的例子是:
<%@ Page Language="C#" %>
<%@ Import Namespace="Newtonsoft.Json" %>
<%
Person[] arr = new[] { new Person { Name = "John" }, new Person { Name = "Jane" } };
string json = JsonConvert.SerializeObject(arr);
%>
<%= json %>
這將完成頁面本身的所有工作,如PHP,並將輸出寫入頁面。
如果您正在使用ASP.NET MVC
public JsonResult GetSomeJson()
{
var myModel = getSomeModel
return Json(myModel);
}
更新 - 所以webforms? 我不做網絡表格,但它是這樣的
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyModel GetSomeJson()
{
MyModel myModel = getSomeModel;
return myModel;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.