c# - 如何在 asp.net 中发回 JSON?

标签 c# asp.net json

假设我在 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/

相关文章:

c# - 如何对一系列数字使用 FindByValue

Asp.net session 几秒后自动过期

javascript - Jquery AJAX json - 未调用

json - 使用不同的键解码相同的 json 对象以进行 slice 结构

c# - 在 Xamarin Mac 中阻止鼠标气泡

c# - 我的应用程序设置应该在 .Net Core/EF Core 类库项目中的什么位置?

c# - 你能从 DbSet 中获取 DbContext 吗?

c# - 如何在 Linq 中实现嵌套 for 循环?

c# - 无法从标签获取 javascript 值

json - 在 Elixir/Phoenix 应用程序中解析 JSON,不是在 Controller 或模型内部,而是从 "/lib"解析