1

我有这样的类结构。问题是当我转移到之前序列化的 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
4

1 回答 1

1

您的 json 格式不正确,因为实体框架对象序列化

你有额外的属性,比如

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

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

于 2013-03-20T09:00:34.273 回答