c# - 需要帮助使用 C# 读取 Json 文件
问题描述
我正在使用 json 文件并尝试使用 C# 读取。
{
"Company": {
"ABC": {"ADDRESS" : "123 STREET",
"DEF" :"ADDRESS 567",
},
},
"Country": {
"Country1": "XYZ",
"Country2" : "ADG",
}
}
在这里,我想检查,如果检索到叶子节点值,则执行一个条件,即公司-> ABC -> 地址->“123” 所以,123 在这里是叶子。
国家 -> 国家 1 -> “XYZ”
XYZ 在这里是叶子。
string jsonFilePath = "D:\\ProjectCode1\\catalogJsonData.json";
string json = File.ReadAllText(jsonFilePath);
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
foreach (var item in json_Dictionary)
{
// parse here
Console.WriteLine("{0} {1}", item.Value);
await context.PostAsync(item.Key);
}
上面的代码我没有为 item.Value 或 item.Key 打印任何值
解决方案
我建议创建一个模型类,您的 json 可以反序列化为使用 Newtonsoft.Json NuGet。我还清理了你的 Json 样本。
杰森:
{
"Company": {
"ABC": {
"ADDRESS": "123 STREET",
"DEF": "ADDRESS 567"
}
},
"Country": {
"Country1": "XYZ",
"Country2": "ADG"
}
}
代码
class JsonModel
{
public IDictionary<string, IDictionary<string, string>> Company { get; set; }
public IDictionary<string, string> Country { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("sample.json");
var jsonModel = JsonConvert.DeserializeObject<JsonModel>(json);
Console.WriteLine("-- Companies-- ");
foreach(var companyDictionary in jsonModel.Company)
{
foreach(var company in companyDictionary.Value)
{
Console.WriteLine($"{company.Key}:{company.Value}");
}
}
Console.WriteLine();
Console.WriteLine("-- Countries --");
foreach (var country in jsonModel.Country)
{
Console.WriteLine($"{country.Key}:{country.Value}");
}
}
}
输出:
推荐阅读
- aws-lambda - Rundeck 运行 AWS Lambda 函数
- python - boto3 已安装但出现 ModuleNotFoundError
- android - 在没有后台位置权限的情况下检测 Android AppWidget 的位置
- android - ExoPlayer如何在加载视频期间显示加载第一帧
- css - 光滑的滑块箭头在 ios (iphone 8) 中被剪切,但在 chrome 和 firefox 中模拟时看起来不错
- windows - 在关闭期间保持进程处于活动状态
- vue.js - 如何在 Nuxt 存储突变中使用 $set?
- android - 元素未添加到 Recycleview
- elasticsearch - 缓冲区刷新比 slow_flush_log_threshold 花费的时间更长
- c++ - F找到具有最小绝对差的第二个数组