【问题标题】:Need help reading Json file using C#需要帮助使用 C# 读取 Json 文件
【发布时间】:2019-12-09 19:49:25
【问题描述】:

我正在使用 json 文件并尝试使用 C# 读取。

{
     "Company": {
               "ABC": {"ADDRESS" : "123 STREET",

            "DEF" :"ADDRESS 567",
            },


           },


     "Country": {

              "Country1": "XYZ",
              "Country2" : "ADG",

              }


 }

在这里,我想检查,如果检索到叶节点值,则执行一个条件,即 Company-> ABC -> Address -> "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 打印任何值

【问题讨论】:

  • Newtonsoft JSON
  • 您是使用此表单还是解析文件,因为这是您知道的唯一方法,还是有其他原因?
  • json 无效,它没有通过所有 RFC; trailing commas present.
  • @Franck 我必须以类似的方式进行映射,但我不确定语法和 RFC。一个节点的最大嵌套级别为 3,最小嵌套级别为 1。
  • @MakeInIndiaInspire 只是,如果您知道格式,您只需创建一个具有适当属性的类并将该类用作反序列化对象,它就会毫无问题地填充。话虽如此,Codexer 提出了一个很好的观点,因为json 甚至无效。在几个没有意义的地方有多余的逗号。如果这是正确的,那么使用类结构很容易解析。

标签: c# json


【解决方案1】:

我建议创建一个模型类,您的 json 可以使用 Newtonsoft.Json NuGet 反序列化。我还清理了你的 Json 样本。

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}");
        }
    }
}

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    相关资源
    最近更新 更多