Phil
Phil

Reputation: 636

C# JsonConvertDeserialization returning null values

I am trying to understand why I am getting null values for the following:

Json:

{
  "IdentityService": {
    "IdentityTtlInSeconds": "90",
    "LookupDelayInMillis": "3000"
  }
}

Class:

public class IdentityService
{
    public string IdentityTtlInSeconds { get; set; }

    public string LookupDelayInMillis { get; set; }
}

Called with :

  _identityService = JsonConvert.DeserializeObject<IdentityService>(itemAsString);

The class is instantiated but the values for IdentityTtlInSeconds and LookupDelayInMillis are null. I cannot see why they should be

Upvotes: 4

Views: 90

Answers (1)

dotnetom
dotnetom

Reputation: 24901

You need one more class - an object which has one property called IdentityService:

public class RootObject
{
    public IdentityService IdentityService { get; set; }
}

You need this class because JSON that you have has one property called IdentityService, and this object has two properties, called IdentityTtlInSeconds and LookupDelayInMillis. If you are using a default serializer your classes need to reflect the structure that you have in your JSON string.

And now you can use it to deserialize your string:

var rootObject = JsonConvert.DeserializeObject<RootObject>(itemAsString);
_identityService = rootObject.IdentityService;

Upvotes: 6

Related Questions