0

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!

3

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.