JsonConvert.DeserializeObject读取对象引用“1”时出错

时间:2018-02-21 18:16:46

标签: c# angularjs json asp.net-web-api

我正在尝试从由角度发布的对象反序列化Web Api中的对象。我收到错误:读取对象引用“1”时出错。 Path'Developers [0] .DeveloperId',第20行,第21位 我的Json对象(已被验证为有效的JSON):

{
  "Id": 0,
  "Name": "Name",
  "OwnerId": 1,
  "Description": "Description",
  "Note": "My Notes",
  "Stakeholders": [
    {
      "$id": "1",
      "StakeholderId": 1,
      "Name": "Mary",
      "DateModified": "2018-02-21T12:28:15.023",
      "DateCreated": "2018-02-21T12:28:15.023",
      "$$hashKey": "object:3"
    }
  ],
  "Developers": [
    {
      "$id": "1",
      "DeveloperId": 1,
      "DeveloperName": "Joseph",
      "DateModified": "2018-02-21T12:28:26.07",
      "DateCreated": "2018-02-21T12:28:26.07",
      "$$hashKey": "object:4"
    }
  ]
}

我正在尝试反序列化:

var app = JsonConvert.DeserializeObject<Application>(request.ToString(), new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

开发人员类(类似于利益相关者类)

public class Developer : IModificationHistory
{
    public int DeveloperId { get; set; }
    [Required]
    public string DeveloperName { get; set; }
    [JsonIgnore]
    public virtual List<Application> Applications { get; set; }
    public DateTime DateModified { get; set; }
    public DateTime DateCreated { get; set; }
}

应用程序类只是:

public class Application
{

    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    public string Note { get; set; }

    public virtual List<Stakeholder> Stakeholders { get; set; }
    public int OwnerId { get; set; }
    public virtual List<Developer> Developers { get; set; }

}

我用来调用这篇文章的javascript是:

    var data =
    {
        Id: vm.appId,
        Name: vm.applicationName,
        OwnerId: vm.owner.DeveloperId,
        Description: vm.applicationDescription,
        Note: vm.note,
        Stakeholders: vm.selectedStakeholders,
        Developers: vm.selectedDevelopers

};


    $http.post("/api/Application/Post/", JSON.stringify(data))

利益相关者列表被正确填充,但开发者列表却没有。如果我把开发人员放在利益相关者之前的列表中,那么开发人员列表就会被正确填充而利益相任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

问题是$id的值相同,两者都设置为1,请参阅内部异常:

  

{“不同的值已经有Id'1'。”}

我刚刚将其值更改为2并且工作正常:

{
  "Id": 0,
  "Name": "Name",
  "OwnerId": 1,
  "Description": "Description",
  "Note": "My Notes",
  "Stakeholders": [
    {
      "$id": "1",
      "StakeholderId": 1,
      "Name": "Mary",
      "DateModified": "2018-02-21T12:28:15.023",
      "DateCreated": "2018-02-21T12:28:15.023",
      "$$hashKey": "object:3"
    }
  ],
  "Developers": [
    {
      "$id": "2",
      "DeveloperId": 1,
      "DeveloperName": "Joseph",
      "DateModified": "2018-02-21T12:28:26.07",
      "DateCreated": "2018-02-21T12:28:26.07",
      "$$hashKey": "object:4"
    }
  ]
}

以下是我输出的屏幕截图:

enter image description here