我是新来的,所以请原谅任何错误的正确问题程序!
基本上,我正在尝试从Pearson Dictionary Web API反序列化json数组。这是JSON(我删除了一些多余的results
索引以节省空间):
{
"status": 200,
"offset": 0,
"limit": 10,
"count": 10,
"total": 47,
"url": "/v2/dictionaries/ldoce5/entries?headword=test",
"results": [
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "test",
"homnum": 1,
"id": "cqAFzDfHTM",
"part_of_speech": "noun",
"pronunciations": [
{
"audio": [
{
"lang": "British English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/gb_pron/brelasdetest.mp3"
},
{
"lang": "American English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/us_pron/test1.mp3"
}
],
"ipa": "test"
}
],
"senses": [
{
"definition": [
"a set of questions, exercises, or practical activities to measure someone's skill, ability, or knowledge"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001626298.mp3"
}
],
"text": "Did you get a good mark in the test ?"
}
],
"gramatical_examples": [
{
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-000592041.mp3"
}
],
"text": "We have a test on irregular verbs tomorrow."
}
],
"pattern": "test on"
}
],
"signpost": "exam"
}
],
"url": "/v2/dictionaries/entries/cqAFzDfHTM"
}
]
}
以下是我用来反序列化上述内容的C#代码:
class Program
{
static void Main(string[] args)
{
string word = "test";
string sURL = "https://api.pearson.com:443/v2/dictionaries/ldoce5/entries?headword=" + word;
WebClient client = new WebClient();
string full = client.DownloadString(sURL);
var final = JsonConvert.DeserializeObject<Dictionary>(full);
Console.WriteLine(final.results[0].senses.definition);
}
}
public class Dictionary
{
public Result[] results { get; set; }
}
public class Result
{
public string part_of_speech { get; set; }
public Senses senses { get; set; }
}
public class Senses
{
public string definition { get; set; }
}
出于某种原因,当我尝试运行它时,我收到了这个奇怪的错误:
无法将当前JSON数组(例如[1,2,3])反序列化为类型 'TestingJson.Senses'因为类型需要JSON对象(例如 {“name”:“value”})正确反序列化。要修复此错误 将JSON更改为JSON对象(例如{“name”:“value”})或更改 反序列化类型为数组或实现集合的类型 接口(例如ICollection,IList)就像List一样 从JSON数组反序列化。也可以添加JsonArrayAttribute 到类型强制它从JSON数组反序列化。路径 'results [0] .senses',第1行,第512位。
非常感谢帮助!
答案 0 :(得分:6)
如果您正在与定义明确的内容(即绝大多数API)进行交互,那么您最好不要创建强类型对象而不是动态或字典。
在Visual Studio中,如果你去.mat
,那么它将生成你需要的所有对象。
.mat