JSON序列化程序将自己的$ id添加到我的对象中

时间:2018-04-26 11:55:47

标签: .net json

我按JSON(listOfObjects)序列化我的实体但是我在JSON结构中不断获得额外的ID。

上课

   [JsonObject(IsReference = true)]
    public class User
    { 
        public Guid id { get; set; }
        public string name { get; set; }
        public string picture { get; set; }
        public string email { get; set; }
        public string skypeLink { get; set; }
        public string title { get; set; }
        public string location { get; set; }
        public string products { get; set; }
        public string organizationUnit { get; set; }
        public string skills { get; set; }
        public string hobbies { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }

        public User() {
            Tags = new HashSet<Tag>();
        }

    }

[JsonObject(IsReference = true)]
public class Tag
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }

}

当我查询我的数据库时:

    [Route("users")]
    [HttpGet]
    public IHttpActionResult getAllUsers()
    {
        var db = new PeopleOfIvantiContext();
        var users = db.Users.ToList();

        return Json( users);
    }

我得到了额外的$id

[
   {
      "$id": "1",
      "Tags": [
         {
            "$id": "2",
            "Users": [
               {
                  "$ref": "1"
               }
            ],
            "Id": "4075f6ee-1073-4567-af27-af08ceef3d14",
            "Name": "SQL"
         },
         {
            "$id": "3",
            "Users": [
               {
                  "$ref": "1"
               }
            ],
            "Id": "4075f6ee-1073-4567-af27-af08ceef3d44",
            "Name": "c#"
         }
      ],
      "id": "4072a7f6-d02b-46ed-8da4-42e37bc47c57",
      "name": "Adam Kowalsky",
      "picture": "YOUR DATA HERE",
      "email": "Adam.kowalsky@gmail.com",
      "skypeLink": "YOUR DATA HERE",
      "title": "Social Worker",
      "location": {
         "imagename": "on.png",
         "x": 10,
         "y": 10
      },
      "products": "Google, Yahoo",
      "organizationUnit": "A",
      "skills": "C#",
      "hobbies": "Running, Reading"
   },
   {

如何摆脱这些$id

1 个答案:

答案 0 :(得分:1)

我想出了如何解决它

[Route("users")]
    [HttpGet]
    public IHttpActionResult GetAllUsers()
    {
        var db = new PeopleOfIvantiContext();
        var users = db.Users.ToList();
        var js = new JsonSerializerSettings();
        js.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        return Json(users, js);
    }