【问题标题】:Binding Json Arrays to model Web Api绑定 Json 数组以建模 Web Api
【发布时间】:2013-03-20 17:09:20
【问题描述】:

我有这样的类结构。问题是当我转移到之前序列化的 web api 控制器用户 json 时,被执行人计数列表为 0。 序列化的 Json 看起来是这样的:

{"$id":"1","UserId":1,"RealName":"vas`ka","PasswordHash":"password",
 "Email":"somemail","Actionees":
   {"$id":"2","$values": 
      [{"$id":"3","ActioneeId":1,"Status":"doing", "CloseDate":null,
        "DeletedFlag":false, "CreationDate":"2013-03-11T11:48:24.08", 
        "Users":null,  "Comments":null}, {"$id":"4","ActioneeId":2,"Status":"doing",  
        "CloseDate":null, "DeletedFlag":false, 
        "CreationDate":"2013-03-11T12:46:08.787", "Users":null,"Comments":null}
      ]
   }
}


public class User
{
    [Key]
    public Int64 UserId { get; set; }
     public String Email { get; set; }
    public String RealName { get; set; }
    public String PasswordHash { get; set; }

    public virtual List<Actionee> Actionees { get; set; }
}

public class Actionee
{
    [Key]
    public Int64 ActioneeId { get; set; }
    public String Status { get; set; }
    public DateTime? CloseDate { get; set; }
    public Boolean DeletedFlag { get; set; }
    public DateTime? CreationDate { get; set; }

    public virtual List<User> Users { get; set; }
    public virtual IEnumerable<Actionee> Comments { get; set; } 
}

我将此字符串添加到 application_start 中:

        var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
        var dcs = new DataContractSerializer(typeof(User), null, int.MaxValue, false,  true, null);
        xml.SetSerializer<User>(dcs);

        var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling =
            Newtonsoft.Json.PreserveReferencesHandling.All;   

       And I tried to deserialized in this way: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

【问题讨论】:

  • 你使用的是 json.net?
  • 没有。我尝试在 WebApi 中使用 newtonsoft 执行此操作,但它可以序列化,但是当我尝试绑定时,没有 Actionees 列表。
  • 能否请您添加一些您的序列化和反序列化代码
  • 好的,您可以通过添加此代码(序列化和反序列化方法)来编辑您的问题吗?我可以测试一下
  • 最后一个问题:字符串结果是实体框架对象序列化的结果?

标签: json entity-framework asp.net-web-api model-binding


【解决方案1】:

你的json格式不好,因为实体框架对象序列化

你有额外的属性,比如

"$id":"2","$values"

JsonFormatter 无法识别这些额外的属性,也无法反序列化您的对象 您需要将您的实体框架对象转换为您的用户对象 在你的 web api 控制器中

【讨论】:

  • 表示我必须使用模型unsted entity framework实体,而且我的模型可能有相同的结构?
  • 是的,另一种选择是使用实体框架strathweb.com/2012/03/…codeproject.com/Articles/468777/…的“代码优先”方法
  • 当我将数据复制到模型时,它不能解决我的结果 json 格式。
  • 我用媒体类型格式化程序解决了这个问题。就像在 msdn 示例中一样。感谢你们对我的帮助。但我关心总是将数据从实体复制到模型。这是正确的方法吗?
  • 尝试使用您的实体框架对象而不是您的用户对象来反序列化它
猜你喜欢
  • 2018-01-30
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-18
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多