【发布时间】:2015-10-06 18:57:57
【问题描述】:
我正在尝试使用 JSON 进行第一次 API 调用以收集啤酒厂信息并收到以下错误:
Newtonsoft.Json.dll 中出现“Newtonsoft.Json.JsonSerializationException”类型的未处理异常
附加信息:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Brewery.Adjunct]”,因为该类型需要 JSON 数组(例如 [1,2,3]) 以正确反序列化。
要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是可以从 JSON 对象反序列化的集合类型(如数组或列表)。 JsonObjectAttribute 也可以添加到类型中,以强制它从 JSON 对象反序列化。
路径“消息”,第 1 行,位置 11。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Brewery
{
class Adjunct
{
//properties
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string category { get; set; }
public string catDisplay { get; set; }
//create list of Adjunct objects
public List<Adjunct> adjuncts{ get; set; }
//address with query for all adjunct items
const string address = "http://api.brewerydb.com/v2/?[MY KEY]/adjunct";
//fill adjuncts with deserialized json data
public void GetBeer(string beer)
{
//initialize beer list
adjuncts = new List<Adjunct>();
//build connection with query and return string
//***static class Connect uses System.net to create web request and web response objects***
string result = Connect.GetConnection(address);
//get list of Adjunct objects
adjuncts = JsonConvert.DeserializeObject<List<Adjunct>>(result);
}
//get Adjunct string
public string PrintData(string sep)
{
return "name: " + name + sep + "id: " + id + sep + "description: " + description;
}
//search adjunct by id
public Adjunct AdjunctByID(int _id)
{
foreach (Adjunct ad in adjuncts)
{
if (_id == id)
{
return ad;
}
}
return null;
}
}
我需要使用不同的 JSON.NET 方法吗?
【问题讨论】:
-
如果您包含您尝试反序列化的 JSON,这将有所帮助。但我的猜测正是错误消息所说的。您正在尝试将属性反序列化到列表
adjucts中,但它不是 JSON 中的数组。 -
我怀疑您的 Adjunct 课程不正确。您可以在此处从 JSON 生成 C# 类:http://json2csharp.com.
-
这里是一个例子:{ id: 876,8.名称:“酸混合物”,9。类别:“杂项”,10。类别显示:“杂项”,11。创建日期:“2013-06-14 12:19:03”12。 },