0

我有一个 Json 字符串,类似于以下内容:

{
   EventID: 4,
   CalendarEntry : 
   {
      CalendarID: 4,
      AreaID: 41,
      Name: "My Event Entry #4"
   }
}

我将顶级结构反序列化为代码中的事件实体,该实体将 (4) 正确添加到 Id:

public class Event
{
    [DataMember(Name = "EventID")]
    public int Id { get; set; }
}

但是,当我将 Calendar 作为属性添加到 Event 时,这两个 Id 总是返回 null?

public class EventCalendar
{
    [DataMember(Name = "CalendarID")]
    public int Id { get; set; }

    [DataMember(Name = "AreaID")]
    public int AreaId { get; set; }

    [DataMember(Name = "Name")]
    public string Name { get; set; }
}

public class Event
{
    [DataMember(Name = "EventID")]
    public int Id { get; set; }

    [DataMember(Name = "CalendarEntry")]
    public EventCalendar Calendar { get; set; }
}

令我烦恼的是,如果我从 Id 或 AreaId 中删除 [DataMember] 属性,并为其命名与我的 JSON 字符串中的名称完全相同,它会返回正确的结果。但是,我不想在我的实体中使用相同的名称,并且希望 [DataMember] 正确带回数据?

我在 .Net 4.5 中使用 JsonSerializer。

我也用 Newtonsoft.Json 试过这个,它做同样的事情吗?

4

2 回答 2

0
{
   EventID: 4,
   CalendarEntry : 
   {
      CalendarID: 4,
      AreaID: 41,
      Name: "My Event Entry #4"
   }
}

也许 :-?

{
   EventID: 4,
   CalendarEntry : 
   [{
      CalendarID: 4,
      AreaID: 41,
      Name: "My Event Entry #4"
   }]
}
于 2012-12-24T10:31:10.627 回答
0

这对我来说很好。验证您的输入 JSON 字符串是否有效。在这个例子中,我使用System.Web.Script.SerializationSystem.Runtime.Serialization

public static void Main (string[] args)
{
        JavaScriptSerializer ser = new JavaScriptSerializer();          
        string json = ser.Serialize(new Event { 
            Id =  4,
            Calendar = new EventCalendar {
                Id = 5,
                AreaId = 55,
                Name = "Some name"
            }
        });

        Console.WriteLine(string.Format("json  = {0}", json));
        Event fromJsonEvent = ser.Deserialize<Event>(json);

        Console.WriteLine(string.Format ("Event.Id = {0}", fromJsonEvent.Id));
        Console.WriteLine(string.Format ("Event.EventCalendar.Name = {0}", fromJsonEvent.Calendar.Name));
        Console.WriteLine(string.Format ("Event.EventCalendar.Id = {0}", fromJsonEvent.Calendar.Id));
    }
}

public class EventCalendar
{
    [DataMember(Name = "CalendarID")]
    public int Id { get; set; }

    [DataMember(Name = "AreaID")]
    public int AreaId { get; set; }

    [DataMember(Name = "Name")]
    public string Name { get; set; }
}

public class Event
{
    [DataMember(Name = "EventID")]
    public int Id { get; set; }

    [DataMember(Name = "CalendarEntry")]
    public EventCalendar Calendar { get; set; }
}
于 2012-12-24T11:08:23.273 回答