列出<object>序列化不使用多个对象</object>

时间:2013-08-23 15:58:40

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

我有以下课程

[DataContract]
public class Video
{
    [Key]
    [DataMember(IsRequired = false)]
    public int VideoId { get; set; }

    [DataMember(IsRequired = false)]
    public int UserId { get; set; }

    [Required]
    [DataMember ]
    public string Title { get; set; }

    [Required]
    [DataMember]
    public virtual IList<Tag> Tags { get; set; }

}

[DataContract]
public class Tag
{
    [Key]
    [Required]
    [DataMember(IsRequired = false)]
    public int? TagId { get; set; }

    [DataMember(IsRequired = true)]
    [Required]
    public string Name { get; set; }

    [IgnoreDataMember]
    public virtual IList<Video> Videos { get; set; }

}

在我的WebAPI控制器中,我称之为:

            var videos = _service.GetVideos();
            return Request.CreateResponse(HttpStatusCode.OK, videos);

这称之为:

    public IList<Video> GetVideos()
    {
        using (var db = CreateContext())
        {
            return db.Videos.Include("Tags").ToList();
        }
    }

然而,通过电线,这就是我得到的:

 [{
    "$id": "8",
    "tags": [
        {
            // CORRECT SERIALIZATION
            "$id": "9",  
            "tagId": 1,
            "name": "Example",
            "count": 5
        }
    ],
    "videoId": 18,
    "userId": 3,
    "title": "Test Video",
    "thumbnail": "http://i.imgur.com/gV3J2Uf.png",
    "source": "test source"
},
 {
    "$id": "19",
    "tags": [
        {
            // WTF?
            "$ref": "9"
        }
    ],
    "videoId": 28,
    "userId": 6,
    "title": "Test Video",
    "thumbnail": "http://i.imgur.com/gV3J2Uf.png",
    "source": "test source"
},
{
    "$id": "20",
    "tags": [
        {
            // CORRECT AGAIN
            "$id": "21",
            "tagId": 10,
            "name": "funny",
            "count": 2
        }
    ],
    "videoId": 29,
    "userId": 6,
    "title": "TEST VID",
    "thumbnail": "https://i.imgur.com/SWOQSOf.jpg",
    "source": "test source"
},
{
    "$id": "22",
    "tags": [
        {
            // INCORRECT
            "$ref": "9"
        },
        {
            "$ref": "21"
        }
    ],
    "videoId": 30,
    "userId": 6,
    "title": "TEST VID",
    "thumbnail": "https://i.imgur.com/R7lVobX.jpg",
    "source": "test source"
}

出于某种原因 - tags有时会正确序列化,有时不会。知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的对象图中有循环引用。它们无法正确进行JSON序列化,序列化程序会检测到这种情况并自动生成引用($ref)。当您使用EF加载对象图时,内存中那些无法在JSON中正确表示的对象之间存在循环引用。

我建议您使用视图模型打破循环引用图,然后通过线路发送视图模型,而不是直接返回自动生成的EF模型。