Search code examples
c#asp.netjsonjson.net

Fetch key from String


Below is the method implemented currently to fetch all the teacherID and store in a list

public async Task<List<string>> GetId(string id)
{
  var teacherID= new List<string>();
                                    
  var responseMessage = @"[
  { 'id': '100','studentId': '001','studentName': 'TestStudent1'},
  {'id': '101','studentId': '002','teacherId': '100','studentName': 'TestStudent2'},
  {'id': '102','studentId': '003','teacherId': '101','studentName': 'TestStudent3'}]";

  var jsonObj = JsonConvert.DeserializeObject<List<JObject>>(responseMessage);

  foreach (var id in jsonObj)
  {
       var Id = id["teacherId"];
       teacherID.Add(Id.ToString());
  }         

 return teacherID;
}

I am getting exception beacause in the first list teacherId is not present. Can any body help me out with this.


Solution

  • Use null check before adding. If key does not exist then null will be returned.

     foreach (var tid in jsonObj)
       {
           var Id = tid["teacherId"];
           if(null!=Id)
            {
               teacherID.Add(Id.ToString());
             }
       } 
    

    Also, method parameter and variable in foreach has same name "id". This will not work. I have changed this in foreach loop.