Harish Kumar

How to parse raw json object with foreach loop with c#

Published on 7 July 2020 · c#

The best way to parse a json string like below is to create an entity class for it (in case if you know what is coming along in the the json object. I mean the fields)


[
    {
        "userName": "Harish",
        "designation": "Full Stack Developer",
        "skills": "c#, javascript"
    }
    {
        "userName": "Rakesh",
        "designation": "Front End Developer",
        "skills": "HTML, CSS,javascript"
    }
]

                

To parse the above json first create a entity class like below


    public partial class userList
    {
        [JsonProperty("userName")]
        public string userName{get; set;}
        
        [JsonProperty("designation")]
        public string designation{get; set;}
        
        [JsonProperty("skills")]
        public string skills{get; set;}
    }

Then you can create the foreach loop by deserializing the json string into userList object


dynamic userObj=JsonConvert.DeserializeObject>(yourJson);
foreach(userList obj in userObj)
{
    var username=obj.userName; // as you defined in the entity class
    var desig=obj.designation; 
    var skills=obj.skills
}

Note: Here we are using the newtonsoft json package. You can install that from nugat packages on your visual studio
reference class:

 using Newtonsoft.Json;