Search code examples
c#jsonjson.netdeserializationjson-deserialization

Newtonsoft JSON DeserializeObject Deserialization of Serialized object


I have the following JSON string being returned that I am trying to deserialize, but I am having problems with it filling in the values for the properties on the object.

Here is the JSON string being returned back:

"{\"ClientData\":[{\"clientID\":9999999,\"userID\":123,\"authID\":\"8a20627be9ec4c608f4c609a24e74174\"}]}"

Now, I have my ClientData class specified via the following:

public class ClientData
{
    [JsonProperty("clientID")]
    public long? ClientID { get; set; }

    [JsonProperty("userID")]
    public int? UserID { get; set; }

    [JsonProperty("authID")]
    public string AuthID { get; set; }
}

What am I doing wrong here in the conversion? I thought it would be as simple as specifying:

var result = JsonConvert.DeserializeObject<ClientData>(auth);

However, this doesn't yield any results. I think the problem may be how the JSON string is being constructed, i.e. the properties defined for the object.

Can someone help point me in the right direction?

Thanks


Solution

  • The data you have is a JSON array wrapped inside another object. You need to create a secondary class, place your ClientData as a list inside that one and deserialize that it.

    Base class that contains your list

    public class ClientDataInformation 
    {
        [JsonProperty("ClientData")]
        public List<ClientData> ClientList {get;set;}
    }
    

    Deserialization

    var result = JsonConvert.DeserializeObject<ClientDataInformation>(auth);