您好,我有这段代码:
通过HttpClient,我收到了这个json字符串:{"group":3,"data":[{"count":1,"providerName":"BetaDigital","providerNo":12},{"count":139,"providerName":"Free to air","providerNo":1}]}
var serializer = new DataContractJsonSerializer(typeof(GroupProvider));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var data = (GroupProvider) serializer.ReadObject(ms);
然后我有这个课程:
[DataContract]
public class GroupProvider
{
public int Group { get; set; }
public DataGroupProvider[] data { get; set; }
}
[DataContract]
public class DataGroupProvider
{
public int Count { get; set; }
public string ProviderName { get; set; }
public int ProviderNo { get; set; }
}
问题是,只有Group被填充且DataGroupProvider为null ..
问题出在哪里?
答案 0 :(得分:2)
正如Data Contract Basics中所述,您要么不放置DataContract
属性,在这种情况下会考虑每个公共属性或字段(但请注意名称应完全匹配)或放置{{ 1}}属性,然后您需要明确标记要使用DataContract
属性考虑的成员。后者还允许您更改名称映射。
因此,您的示例JSon可以使用此数据模型进行反序列化(请注意属性名称大小写):
DataMember
或保留您当前的媒体名称:
public class GroupProvider
{
public int group { get; set; }
public DataGroupProvider[] data { get; set; }
}
public class DataGroupProvider
{
public int count { get; set; }
public string providerName { get; set; }
public int providerNo { get; set; }
}
答案 1 :(得分:0)
像这样设置DataMember-Attribute:
[DataContract]
public class GroupProvider
{
[DataMember]
public int Group { get; set; }
[DataMember]
public DataGroupProvider[] data { get; set; }
}
[DataContract]
public class DataGroupProvider
{
[DataMember]
public int Count { get; set; }
[DataMember]
public string ProviderName { get; set; }
[DataMember]
public int ProviderNo { get; set; }
}
然后将您的JSON更改为正确的JSON:
var str ="{\"Group\":3,\"data\":[{\"Count\":1,\"ProviderName\":\"BetaDigital\",\"ProviderNo\":12},{\"Count\":139,\"ProviderName\":\"Free to air\",\"ProviderNo\":1}]}";
JSON-Data CaseSensitive