Shravan Kumar

Shravan Kumar

  • NA
  • 3
  • 66.5k

How to Deserialize a JSON array in C#

Jul 21 2015 2:34 AM

I am struggling with a subject that has a lot of variants in this forum but I can't seem to find one that suits me, and I think it's because of the way that my JSON array is :( I'm not an expert but I already manage to "almost" get the end.. I need to get hand in "Status" and "listOfCredDetails" value.

My JSON (is called responseFromServer):

 { "Status": 
     { "StatusCode":143, "SubStatus":0, "Description":"Ok" },
  "ListofCredDetails":
     [{ "Client":"a", "CredID":111, "CredUserID":"abc" },
      { "Client":"b", "CredID":112, "CredUserID":"def" },
      { "Client":"c", "CredID":113, "CredUserID":"ghi" }] 
 }
Then, based on lot of examples in this forum, taking bits and pieces I created my classes:
[Serializable] 
public class StatusReturn 
{ 
public int StatusCode { get; set; } 
public int SubStatus { get; set; } 
public string Description { get; set; } 
}
 [Serializable] 

public class CredDetailsReturn 
{ 
public string Client{ get; set; } 
public int CredID{ get; set; } 
public string CredUserID{ get; set; } 
 }
 
[Serializable]
 public class GetUserCredentialDetailsReturn
 { 
public StatusReturn status;
 public List<CredDetailsReturn> listOfCredDetails;
 public GetUserCredentialDetailsReturn() 
      {         
          status = new StatusReturn(); 
          listOfCredDetails = new List<CredDetailsReturn>(); 
       } 
}

Then Am going to deserialize to get

1."Status" and its elements into one object and

2."ListofCredDetails" and its List of elements into one object

and then creating object for "GetUserCredentialDetailsReturn" to return both status(object) and ListofCredDetails(object) at a time.

Can anyone help me understand how can i achieve this i have tried some like below to deserialize and to get Json data into two seperate objects.

But it is not working....

public GetUserCredentialDetailsReturn InvokeRequest(RESTInvokeClass objInvoke)
 { 
... 
...         
 using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
     { 
          string responseText = streamReader.ReadToEnd();
          GetUserCredentialDetailsReturn result = new GetUserCredentialDetailsReturn(); 
          result.status = JsonConvert.DeserializeObject<StatusReturn>(responseText);
          result.listOfCredDetails  = JsonConvert.DeserializeObject<List<CredDetailsReturn>>(responseText); 
          return result; 
      } 
}
 

Answers (6)