【发布时间】:2017-05-07 10:51:20
【问题描述】:
利用 C# Newtownsoft JSON 库...我遇到了这个问题。
搭建舞台……
我有这个来自 RESTful Web 服务的 JSON:
[
{
"CorporateArea": "Brampton",
"ServiceAddress": "321 Heart Lake Road",
"VendorName": "Enbridge Gas Distribution Inc",
"MeterNumber": "502105",
"RateClass": "NG-R6",
"Department": "22603",
"Account": "12008",
"VendorID": "0000001195",
"MeterLevelID": 2882,
"SiteAddressID": 468,
"MappingLocation": "Beckett Sproule",
"ElectricalBilling": "",
"EnergyLine": "",
"CorporateGroup": "Public Works"
}
]
我也有这些 C# 类:
public class AccountInfo
{
[JsonProperty("Account")]
public string Account { get; set; }
[JsonProperty("CorporateArea")]
public string CorporateArea { get; set; }
[JsonProperty("CorporateGroup")]
public string CorporateGroup { get; set; }
[JsonProperty("Department")]
public string Department { get; set; }
[JsonProperty("ElectricalBilling")]
public string ElectricalBilling { get; set; }
[JsonProperty("EnergyLine")]
public string EnergyLine { get; set; }
[JsonProperty("MappingLocation")]
public string MappingLocation { get; set; }
[JsonProperty("MeterLevelID")]
public string MeterLevelID { get; set; }
[JsonProperty("MeterNumber")]
public string MeterNumber { get; set; }
[JsonProperty("RateClass")]
public string RateClass { get; set; }
[JsonProperty("ServiceAddress")]
public string ServiceAddress { get; set; }
[JsonProperty("SiteAddressID")]
public string SiteAddressID { get; set; }
[JsonProperty("VendorID")]
public string VendorID { get; set; }
[JsonProperty("VendorName")]
public string VendorName { get; set; }
}
public class JSONArray {
public IList<AccountInfo> AccountsInfo { get; set; }
}
从这些,我称之为 Newtownsoft 方法:
JSONArray Accounts = JsonConvert.DeserializeObject<JSONArray> (responseBody,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
但是每次我这样做时,我都会收到异常 Newtonsoft.Json.JsonSerializationException 带有错误消息:
错误转换值 "[{"CorporateArea":"Brampton","ServiceAddress":"321 Heart Lake Road","VendorName":"Enbridge Gas Distribution Inc","MeterNumber":"502105","RateClass" :"NG-R6","部门":"22603","帐户":"12008","VendorID":"0000001195","MeterLevelID":2882,"SiteAddressID":468,"MappingLocation":"Beckett Sproule ","ElectricalBilling":"","EnergyLine":"","CorporateGroup":"Public Works"}]" 输入 'TestWebService_Consume.JSONArray'。路径 '',第 1 行,位置 421。
我尝试将 JSON 字符串弄乱,使其不是数组,并将其转换为简单的 AccountsInfo 对象,它返回相同的错误。
我一定是做错了什么,但是自从我使用 Newtonsoft JSON 库以来已经有一段时间了,所以我不知道这里可能存在什么问题。
【问题讨论】:
标签: c# json web-services rest json.net