【发布时间】:2020-06-09 15:53:45
【问题描述】:
我在尝试从以下 JSON 表中提取数据时遇到困难:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
我的目标是为每个“单词”和每个“定义”获取一个字符串输出。我有以下对应于 JSON 文件的类:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
最后这段代码应该是从字符串结果中的表中检索第一个单词:
var list = JsonConvert.DeserializeObject<List<Dictionary.Rootobject>>(rawJSON);
string result = list[0].Property1[0].data[0].word;
.Property[0] 返回 null 并且程序给了我一个 null 引用异常。我的代码哪里出错了,我应该如何完成这项任务?谢谢。
编辑: 我不确定这是否会弄乱 rawJSON 字符串,但我是这样理解的:
rawJSON = File.ReadAllText(FileSystem.AppDataDirectory + fileName);
【问题讨论】:
-
能否提供一个完整有效的json内容?否则很难找出问题所在。
-
数据中的前两个元素没有“数据”属性。你真的检查过反序列化的 json 吗?
-
您可以在 Visual Studio 中复制您的 json 并选择性粘贴以创建适当的类,或使用 www.json2csharp.com 站点查看正确反序列化 json 所需的类
-
请查看minimal reproducible example 发布代码指南并相应地发布edit。特别要确保提供准确(但最少)的 JSON 来证明问题。此外,由于它是 NRE,请务必查看 stackoverflow.com/questions/4660142/…。
-
我很乐意提供帮助,但如果没有有效的 json 示例,我将无法提供帮助。