jradata
jradata

Reputation: 59

C# Deserialization of JSON for use in a foreach loop

I have json that is posted from a HTTP req. I am trying to deserialize it for use in a for each loop. Unfortunately, its format is kicking my ass as its a list of objects (i believe).

so far i have the following:

dynamic jsonObj = JsonConvert.DeserializeObject(await req.ReadAsStringAsync());

foreach (var p in jsonObj.hireSchedules)
    {
     ///do something
    }

My json is as below:

{
"hireSchedules": [
    {
        "plant": "7246054",
        "num" : "79",
        "hire": "1137277"
     },
    {
        "plant": "7246055",
        "num" : "80",
        "hire": "1137278"
     }
    ]
}

I have the following classes:

public class HireSchedule
{
    public string plant { get; set; }
    public string num { get; set; }
    public string hire { get; set; }
}

public class RootObject
{
    public List<HireSchedule> hireSchedules { get; set; }
}

Any help would be appreciated. Thanks!

Upvotes: 2

Views: 8493

Answers (2)

Prany
Prany

Reputation: 2133

One of the way is to use Newtonsoft.json nuget which is really very powerful, so

var files = JObject.Parse(YourJSON);
var recList = files.SelectTokens("$..hireSchedules").ToList();
foreach (JObject obj in recList.Children())
 {
   foreach (JProperty prop in obj.Children())
      {
        var key = prop.Name.ToString();
        var value = prop.Value.ToString();
         //Do your stuffs here
      }

  }

Upvotes: 1

NotFound
NotFound

Reputation: 6157

Since you have already defined the classes it's easy enough to deserialize it into them. Then you have a strongly typed class and the IDE should be able to help you out how to access the properties.

var json = File.ReadAllText("json1.json");
var root = JsonConvert.DeserializeObject<RootObject>(json);

foreach (var p in root.hireSchedules)
{
    ///do something
}

Upvotes: 4

Related Questions