Reputation: 13
I want deserialize this object from JSON:
{"domain":"google.com","data":{"available":true,"expiration":null,"registrant_email":null}}
I use this code:
public class Data
{
public string available { get; set; }
}
Data data = JsonConvert.DeserializeObject<Data>(finishResponse);
Console.WriteLine(data.available);
please help me for it!
Upvotes: 0
Views: 233
Reputation: 26450
Try with this change. This way your C# classes will match the JSON object your are receiving. You should of course extend the Data
class to include the rest of the json fields if they are of interest to you.
public class Response
{
[JsonProperty(Required = Required.Default)]
public string Domain { get; set; }
[JsonProperty(Required = Required.Always)]
public Data Data { get; set; }
}
You will notice that I added the required to AllowNull
for Expiration
+RegistrantEmail
and the Data
property to Always
. If you send null for Data
the deserialization will fail.
public partial class Data
{
[JsonProperty(Required = Required.Default)]
public bool Available { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public object Expiration { get; set; }
[JsonProperty("registrant_email" ,Required = Required.AllowNull)]
public object RegistrantEmail { get; set; }
}
var response = JsonConvert.DeserializeObject<Response>(finishResponse);
Console.WriteLine(response.Data.available);
This answer also considers some of the fields in your serialized json string may be null and thus won't throw exception if that's the case.
Upvotes: 1
Reputation: 82534
Your class doesn't match the JSON... Here are a couple of classes that do match the JSON:
public class MyJson
{
[JsonProperty("domain")]
public string Domain { get; set; }
[JsonProperty("data")]
public Data Data { get; set; }
}
public partial class Data
{
[JsonProperty("available")]
public bool Available { get; set; }
// This should probably be a nullable DateTime
[JsonProperty("expiration")]
public object Expiration { get; set; }
// And this should probably be a string...
[JsonProperty("registrant_email")]
public object RegistrantEmail { get; set; }
}
I've generated them online directly from your JSON.
Upvotes: 0