Json.net无法反序列化复杂类型列表

时间:2012-04-12 13:23:47

标签: wcf json.net wcf-rest

我使用json.net在IIS托管的restful服务中执行处理我的json反序列化。

首先,这是我尝试使用的对象。

[DataContract]
public class CreateSamplesRequest
{
    [DataMember] public Guid SessionId { get; set; }
    [DataMember] public SampleTemplateDTO Template { get; set; }
}
[DataContract]
public class SampleTemplateDTO
{
    [DataMember] public int NumberOfSamples { get; set; }
    [DataMember] public int CompanyId { get; set; }
    [DataMember] public int SampleTypeId { get; set; }
    [DataMember] public HmisDTO Hmis { get; set; }
    [DataMember] public List<AttributeValueDTO> AttributeValues { get; set; }   
}
[DataContract]
public class AttributeValueDTO
{
    [DataMember] public int AttributeId { get; set; }
    [DataMember] public string AttributeName { get; set; }
    [DataMember] public string Value { get; set; }
}

[DataContract]
public class HmisDTO
{
    [DataMember] public string Health { get; set; }
    [DataMember] public string Flammability { get; set; }
    [DataMember] public string Reactivity { get; set; }
    [DataMember] public string Equipment { get; set; }
}

帮助页面以CreateZamplesRequest

的格式请求json
{
 "SessionId":"1627aea5-8e0a-4371-9022-9b504344e724",
 "Template":{
    "NumberOfSamples":2147483647,
    "CompanyId":2147483647,
    "SampleTypeId":2147483647,
    "Hmis":{
        "Health":"String content",
        "Flammability":"String content",
        "Reactivity":"String content",
        "Equipment":"String content"
    },
    "AttributeValues":[{
        "AttributeId":2147483647,
        "AttributeName":"String content",
        "Value":"String content"
    }]
  }
}

这就是我实际发送的内容:

{
 "SessionId":"17aaec11-be28-4536-b5df-d98fbda91e91",
 "Template":{
    "NumberOfSamples":1,
    "CompanyId":1,
    "SampleTypeId":9,
    "Hmis":{
        "Health":"2",
        "Flammability":"0",
        "Reactivity":"0",
        "Equipment":"E",
    },
   "AttributeValues":[
      {"AttributeId":1,"AttributeName":"Item No.","Value":"MN0002NG"},
      {"AttributeId":2,"AttributeName":"Lot No.","Value":"C4526"}
    ]
 }
}

我遇到的问题是SampleTemplateDTO对象的AttributeValues属性总是被忽略。使用上面的代码,它将为null。如果我将它实例化为空List<AttributeValueDTO>,它将是一个空列表。几个小时后我一直在敲打着我。

我尝试创建一个只需List<AttributeValueDTO>的服务,但它运行正常。我尝试为AttributeValues创建一个包装类,它仍然以null结尾。我完全难过了。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

上帝的母亲,我只是浪费了5小时的爆发力。 HMIS部分中的尾随逗号显然告诉json.net在此时停止解析。

当我提交这个json:

{
 "SessionId":"17aaec11-be28-4536-b5df-d98fbda91e91",
 "Template":{
  "NumberOfSamples":1,
  "CompanyId":1,
  "SampleTypeId":9,
  "Hmis":{
    "Health":"2",
    "Flammability":"0",
    "Reactivity":"0",
    "Equipment":"E"
  },    
  "AttributeValues":[
   {"AttributeId":1,"AttributeName":"Item No.","Value":"MN0002NG"},
   {"AttributeId":2,"AttributeName":"Lot No.","Value":"C4526"}
  ]     
 }
}

一切都很好。