MakeInIndia Inspire
MakeInIndia Inspire

Reputation: 19

Need help reading Json file using C#

I am using json file and trying to read using C#.

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

            "DEF" :"ADDRESS 567",
            },


           },


     "Country": {

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

              }


 }

Here, I want to check ,if the leaf node value is retrieved,then execute a condition i.e Company-> ABC -> Address -> "123" So, 123 is leaf here.

Country -> Country1 -> "XYZ"

XYZ is leaf here .

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

Above code i am not getting any value printed for item.Value or item.Key

Upvotes: 0

Views: 96

Answers (1)

sspaniel
sspaniel

Reputation: 677

I recommend creating a model class that your json can be deserialized to using the Newtonsoft.Json NuGet. I also cleaned your Json sample.

Json:

{
  "Company": {
    "ABC": {
      "ADDRESS": "123 STREET",
      "DEF": "ADDRESS 567"
    }
  },
  "Country": {
    "Country1": "XYZ",
    "Country2": "ADG"
  }
}

Code

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

Output:

enter image description here

Upvotes: 2

Related Questions