【问题标题】:in c#, how do i convert this data structure into Json在 C# 中,我如何将此数据结构转换为 Json
【发布时间】:2011-04-08 05:05:13
【问题描述】:

在 C# 中,我有一个 日历 对象数组

每个 Calendar 对象都有一个 CalendarEvent 对象数组

每个 CalendarEvent 对象都有一个 DateName 属性

我想将此转换为 Json 对象,但我想稍微更改数据结构,因此在 json 对象中,日历是日期数组和名称数组(分解 CalendarEvent 对象)

我想要这样的东西:

var myObject = return Json(new
                {
                    Calendars = new[]
                    {
                         Dates = new [] {myDateArray};
                         Names = new [] {myNameArray};
                    }
                }

【问题讨论】:

    标签: c# javascript asp.net-mvc arrays json


    【解决方案1】:
    IEnumerable<Calendar> calendars = ...
    
    return Json(
        calendars.Select(calendar => new
        {
            Names = calendar.CalendarEvents.Select(e => e.Name),
            Dates = calendar.CalendarEvents.Select(e => e.Date)
        })
    );
    

    【讨论】:

      【解决方案2】:

      对于 .Net 3.5,您需要查找 DataContractJsonSerializer。你可能想要customise it 来匹配你想要的。

      【讨论】:

      • 哦不,为什么要重新发明轮子?当Json 方法已经这样做时,您是否建议手动使用序列化程序?
      • 哦,我没有意识到 .Net 有一个 Json 对象/方法。 msdn 参考?
      猜你喜欢
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多