假设我在 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 %>
关于c# - 如何在 asp.net 中发回 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15123125/