简体   繁体   中英

How to Deserialize a JSON array in C#

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; 

        }

    }
[Serializable]
public class GetUserCredentialDetailsReturn
{
    public StatusReturn status { get; set; }
    public List<CredDetailsReturn> listOfCredDetails { get; set; }
}

JsonConvert.Deserialize<GetUserCredentialDetailsReturn>(json_string)

If you need just some isolated elements of a (say very large) JSON File you need the lower level parts of the JSON Library, for example from Newtonsoft:

using Newtonsoft.Json;

Then create a parser which reads through the JSON Tokens:

var reader = new JsonTextReader(...);

You'll get token by token:

    private void nextToken()
    {
        do
        {
            if (!reader.Read()) this.importError("unexpected end of file");
        }
        while (reader.TokenType == JsonToken.Comment);
    }

and have to handle this in a Token Parser. For example if you read an array:

    private void readMyArray()
    {
        // StartArray
        if (reader.TokenType != JsonToken.StartArray) this.importError("expected start of array '['");
        this.nextToken();

        while (reader.TokenType != JsonToken.EndArray)
        {
            this.readMyElement();
        }            
        // EndArray
        if (reader.TokenType != JsonToken.EndArray) this.importError("expected end of array ']'");
        this.nextToken();
    }

This technique is explained in every book about building compilers.

You need to first change your property names in the class GetUserCredentialDetailsReturn as status to Status and listOfCredDetails to ListofCredDetails.

Then you can try to de-serialize your Json into your class GetUserCredentialDetailsReturn by the code below.

GetUserCredentialDetailsReturn result = new GetUserCredentialDetailsReturn();
result = JsonConvert.DeserializeObject<GetUserCredentialDetailsReturn>(responseText);

You can get your status and listOfCredDetails with in the result.

   // result.Status
   // result.ListofCredDetails

Hope this will be helpful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM