【发布时间】:2017-10-03 21:30:36
【问题描述】:
我有以下 JSON,我正在编写要反序列化的对象模型:
{
"company_webhooks": [
{
"company_webhook": {
"id": 42,
"url": "https://keeptruckin.com/callbacktest/842b02",
"secret": "fe8b75de0a4e5898f0011faeb8c93654",
"format": "json",
"actions": [
"vehicle_location_received",
"vehicle_location_updated"
],
"enabled": false
}
},
{
"company_webhook": {
"id": 43,
"url": "https://keeptruckin.com/callbacktest/a6a783",
"secret": "66a7368063cb21887f546c7af91be59c",
"format": "json",
"actions": [
"vehicle_location_received",
"vehicle_location_updated"
],
"enabled": false
}
},
{
"company_webhook": {
"id": 44,
"url": "https://keeptruckin.com/callbacktest/53a52c",
"secret": "4451dc96513b3a67107466dd2c4d9589",
"format": "json",
"actions": [
"vehicle_location_received",
"vehicle_location_updated"
],
"enabled": false
}
},
{
"company_webhook": {
"id": 45,
"url": "https://keeptruckin.com/callbacktest/6fb337",
"secret": "4177fbd88c30faaee03a4362648bd663",
"format": "json",
"actions": [
"vehicle_location_received",
"vehicle_location_updated"
],
"enabled": false
}
},
{
"company_webhook": {
"id": 46,
"url": "https://keeptruckin.com/callbacktest/8cd6da",
"secret": "6e41817a048b009435e5102fca17db55",
"format": "json",
"actions": [
"vehicle_location_received",
"vehicle_location_updated"
],
"enabled": false
}
}
],
"pagination": {
"per_page": 25,
"page_no": 1,
"total": 5
}
}
这是我所拥有的:
[DataContract]
public class KeepTruckinResponse
{
[DataMember(Name = "company_webhooks", EmitDefaultValue = false)]
public KeepTruckinCompanyWebHook[] WebHooks { get; set; }
[DataMember(Name = "pagination", EmitDefaultValue = false)]
public KeepTruckinPagination Pagination { get; set; }
public string RawJSON { get; set; }
}
[DataContract]
public class KeepTruckinPagination
{
[DataMember(Name = "per_page", EmitDefaultValue = false)]
public int PerPage { get; set; }
[DataMember(Name = "page_no", EmitDefaultValue = false)]
public int PageNumber { get; set; }
[DataMember(Name = "total", EmitDefaultValue = false)]
public int Total { get; set; }
}
[DataContract(Name = "company_webhook")]
public class KeepTruckinCompanyWebHook
{
[DataMember(Name = "id", EmitDefaultValue = false)]
public int Id { get; set; }
[DataMember(Name = "url", EmitDefaultValue = false)]
public string Url { get; set; }
}
显然,当我反序列化 JSON 时,我没有得到 KeepTruckinCompanyWebHook 属性,因为它们发送集合的方式是“嵌套的”。我几乎必须在 KeepTruckinCompanyWebHook 中创建另一个带有属性的对象。但我想保持我的对象模型不变。 .NET 序列化器可以吗?
我们像这样使用DataContractJsonSerializer:
var ser = new DataContractJsonSerializer(typeof(KeepTruckinResponse));
response = ser.ReadObject(ms) as KeepTruckinResponse;
此时我们不想使用 NewtonSoft.Json
【问题讨论】:
-
编辑您的问题以表明您正在序列化数据。通常避免使用
DataContract,而是使用更多使用的NewtonSoft.Json属性 -
“显然,当我反序列化 JSON 时,我没有得到 KeepTruckinCompanyWebHook 属性,因为它们发送集合的方式是嵌套的”不知道你的意思。作为使用 Newtonsoft 的人,我非常希望它能够被反序列化。
标签: c# .net json serialization datacontractjsonserializer