Newtonsoft解析JSON遇序列化异常,如何正确转换数据?
如何使用Newtonsoft转换目标JSON字符串?
我来帮你搞定这个Newtonsoft.Json的反序列化问题!
先看你提供的JSON结构:它的根是一个对象,里面包含了一个名为geonames的数组,数组里每一项都是具体的国家信息对象。你之前抛出的JsonSerializationException,核心原因是反序列化的类型和JSON结构不匹配——你可能尝试直接把JSON反序列化成单个国家对象或者List<GeonamesCountry>,但JSON的根并不是数组,而是一个包裹着数组的对象,所以才会提示“无法将JSON数组反序列化为需要JSON对象的类型”。
下面是正确的解决方案:
1. 定义匹配JSON结构的模型类
你需要先创建一个包装类来对应JSON的根对象,再定义国家信息的实体类来匹配数组里的每一项:
public class GeonamesObject { public GeonamesCountry[] geonames { get; set; } } public class GeonamesCountry { public string countryCode { get; set; } public string countryName { get; set; } public string isoNumeric { get; set; } public string isoAlpha3 { get; set; } public string fipsCode { get; set; } public string continent { get; set; } public string continentName { get; set; } public string capital { get; set; } public string areaInSqKm { get; set; } public string population { get; set; } public string currencyCode { get; set; } public string languages { get; set; } public int geonameId { get; set; } public string west { get; set; } public string north { get; set; } public string east { get; set; } public string south { get; set; } public string postalCodeFormat { get; set; } }
2. 执行正确的反序列化操作
在你的控制器代码中,将下载到的JSON字符串反序列化为GeonamesObject类型,这样就能正确解析出根对象里的geonames数组了:
string GeoNamesCountry = "http://api.geonames.org/countryInfo?username=justlearntutors&type=json"; string GeoNamesCountryResult = ""; using (WebClient webclient = new WebClient()) { GeoNamesCountryResult = webclient.DownloadString(GeoNamesCountry); } GeonamesObject geonamesObject = Newtonsoft.Json.JsonConvert.DeserializeObject<GeonamesObject>(GeoNamesCountryResult);
完成后,你就可以通过geonamesObject.geonames访问到所有国家的信息数组啦。
内容的提问来源于stack exchange,提问作者Philip Rossen
相关产品推荐
相关产品推荐

