c# - 用字典或列表作为值读取 Json 文件 C#
问题描述
我有这个 json 文件:
[{
"images": "hello",
"id": [{"value": 0, "url": "https://en.wikipedia", "content": "Since 200"}],
"answers": ["whole."],
"type": "description",
"row": "what is rba"
},
{
"images": "hello2",
"id": [{"value": 1, "url": "https://en.wikipedia2", "content": "Since 2002"}],
"answers": ["whole."],
"type": "description2",
"row": "what is rba2"
}]
我需要阅读这个文件并将每个键存储在一个列表中。我尝试了两种不同的方法:
我尝试的第一种方法是:
static void Main(string[] args)
{
string filePath = @"C:\Users\corve\OneDrive\Escritorio\file.json";
string jsonString;
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (var streamReader2 = new StreamReader(fileStream, Encoding.UTF8))
{
jsonString = streamReader2.ReadToEnd();
}
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
var urls = new List<string>();
foreach (var file in result.id)
{
urls.Add(file.url);
}
foreach (var item in urls)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
然后第二种方法是:
StreamReader streamReader = new StreamReader(filePath);
JsonTextReader JTextreader = new JsonTextReader(streamReader);
JTextreader.SupportMultipleContent = true;
var serializer = new JsonSerializer();
while (JTextreader.Read())
{
if (JTextreader.TokenType == JsonToken.StartObject)
{
Passeges p = serializer.Deserialize<Passeges>(JTextreader);
Console.WriteLine(p.type + " "+ p.row + " " );
}
}
在哪里:
class Passeges
{
public string images { get; set; }
public string id { get; set; }
public string answers { get; set; }
public string type { get; set; }
public string row { get; set; }
public string value { get; set; }
public string url { get; set; }
public string content { get; set; }
}
然而,两者都导致了错误。第一个:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“Newtonsoft.Json.Linq.JArray”不包含“id”的定义
第二个:
Newtonsoft.Json.JsonReaderException:'解析值时遇到意外字符:[。路径“[0].id”,第 3 行,位置 8。
任何想法如何解决它或做到这一点?
解决方案
这很容易
static void Main(string[] args)
{
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Response[]>(jsonString);
var urls = new List<string>();
foreach (var response in result)
{
foreach (var id in response.id)
{
urls.Add(id.url);
Console.WriteLine(id.url);
}
}
Console.ReadLine();
}
你的模型对象应该是:
public class Response
{
public string images { get; set; }
public Url[] id { get; set; }
public string[] answers { get; set; }
public string type { get; set; }
public string row { get; set; }
}
public class Url
{
public int value { get; set; }
public string url { get; set; }
public string content { get; set; }
}
推荐阅读
- elasticsearch - Elasticsearch 不会在我的 ELK 实例上重新启动时自动启动
- c# - .net 核心控制台日志和命令
- android - 无法确定任务“:app:processDebugResources”的依赖关系
- r - 按组复制控制行
- angular - 如何等待订阅完成管道和地图
- pandas - 使用 Pandas 从不同位置的固定宽度文件中读取数据
- c++ - 我如何在头文件和类文件中将其分开?
- python-3.x - 显示 2 位小数,并在 pandas 中使用逗号作为分隔符?
- python - Discord.py 制作队列命令
- typescript - 如何在 TypeScript 中获取 JSON 文件上的 Object.keys 时设置类型?