首页 > 解决方案 > 需要帮助使用 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 打印任何值

标签: c#json

解决方案


我建议创建一个模型类,您的 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}");
        }
    }
}

输出:

在此处输入图像描述


推荐阅读