【发布时间】:2017-09-18 05:49:46
【问题描述】:
我正在尝试对从 API 返回的一些 JSON 进行反序列化,以便循环遍历县名数组并将信息添加到 C# 中的数据表中。但是,当我尝试反序列化它时,我在第一个障碍中收到以下错误:
错误:System.MissingMethodException:没有为“DPDJSONLibrary.DPD_JSON+LOCR_Data[]”类型定义无参数构造函数。
API 的提供者提供如下 JSON 响应示例:
{
"error": null,
"data":[{
"country": [{
"countryCode":"GB",
"countryName":"United Kingdom",
"internalCode":"UK",
"isEUCountry":false,
"isLiabilityAllowed":false,
"isoCode":"826",
"isPostcodeRequired":false,
"liabilityMax":15000
}]
}]
}
我从 API 返回的 JSON 数据示例是:
{
"data": {
"country":[
{
"countryCode":"PM",
"countryName":"St Pierre & Miquilon",
"isoCode":"666",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SR",
"countryName":"Suriname",
"isoCode":"740",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SZ",
"countryName":"Swaziland",
"isoCode":"748",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
}
]
}
}
我尝试制作一些类来将 JSON 放入如下:
/// <summary>
/// List Of Countries Response object.
/// </summary>
public class LOCR
{
public LOCR_Error error { get; set; }
public LOCR_Data[] data { get; set; }
}
public class LOCR_Error
{
public string errorAction { get; set; }
public string errorCode { get; set; }
public string errorMessage { get; set; }
public string errorObj { get; set; }
public string errorType { get; set; }
}
public class LOCR_Data
{
public LOCR_Data_Country[] country { get; set; }
}
public class LOCR_Data_Country
{
public string countryCode { get; set; }
public string countryName { get; set; }
public string internalCode { get; set; }
public bool isEUCountry { get; set; }
public bool isLiabilityAllowed { get; set; }
public string isoCode { get; set; }
public bool isPostcodeRequired { get; set; }
public int liabilityMax { get; set; }
}
当我将 JSON 作为字符串返回时,我正在尝试使用 Newtonsoft(插件?)将其放入我的类中:
JavaScriptSerializer ser = new JavaScriptSerializer();
DPD_JSON.LOCR DPDCountries = new DPD_JSON.LOCR();
DPDCountries = ser.Deserialize<DPD_JSON.LOCR>(data);
产生错误的是上面的最后一行。我怀疑我写错了我试图反序列化 JSON 的类 - 任何人都可以看到我哪里出错了吗?
【问题讨论】:
-
这应该可以正常工作,你可以尝试使用
List<LOCR_Data>而不是LOCR_Data[]吗? -
您的 Json 无效 - 数组中的最后一个元素后面有逗号。
-
我已从帖子中的数据中删除了最后一个逗号 - 这是我的错。我从 API 返回的数据包含数百行,因此我删除了其中大部分,因此帖子不会太长。我错过了最后一个逗号。
标签: c# json serialization