1

I have been working on some automated tests with selenium and I need to get some data out of a JSON file.

how can i go about coding this, i have this so far

string json = File.ReadAllText("myfilepath");
dynamic data = jsonConvert.DeserializeObject(json);
string x = data[0].CountryName.Value;


foreach(var CN in data.countryName)
{
    var CountryName = CN.CountryName;
}

I am a bit stuck on getting data through to loop it Any help would be amazing guys

Example Json :

[
   {
       "CountryLookupId":123,
       "CountryName":data,
       "CountryLocation": moredata
   }
]

I am trying to loop through the CountryName,i need to loop through 31 things

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
  • 1
    how does your json looks like, share simple exmaple – Maytham Fahmi Jun 09 '20 at 16:42
  • I have edited the post for you :) – WannabeCodeMonkey Jun 09 '20 at 16:48
  • 1
    @WannabeCodeMonkey, use [Newtonsoft.Json](https://www.newtonsoft.com/json) to parse your [string to JArray](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JArray_Parse.htm). I added fiddle, please look into it -> https://dotnetfiddle.net/e8i5Nq – Prasad Telkikar Jun 09 '20 at 17:00
  • I will implement this and will let you know how it turns out, thanks for your help :) – WannabeCodeMonkey Jun 09 '20 at 17:04
  • Or better yet create a strongly typed data model using one of the tools from [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182) then deserialize to a `List` and loop through the results. – dbc Jun 09 '20 at 17:13

1 Answers1

1

With out testing it. make a object model:

public class CountryClass
{
    [JsonProperty("CountryLookupId")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long CountryLookupId { get; set; }

    [JsonProperty("CountryName")]
    public string CountryName { get; set; }

    [JsonProperty("CountryLocation")]
    public string CountryLocation { get; set; }
}

Than deserialize list of object model:

List<CountryClass> data = jsonConvert.DeserializeObject<List<CountryClass>>(json);

Finally you can loop over your list of country objects:

foreach(var cn in data)
{
    var countryName = cn.CountryName;
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137