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!

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 2
    [Knock yourself out...](https://app.quicktype.io/#l=cs&r=json2csharp) – Zohar Peled Dec 15 '19 at 07:58
  • Your root data model does not match your JSON. To generate a correct data model automatically, see [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182). – dbc Dec 15 '19 at 08:01
  • possible duplicate : https://stackoverflow.com/questions/34302845/deserialize-json-into-object-c-sharp – Omar AMEZOUG Dec 15 '19 at 08:59

2 Answers2

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.

Sina Hoseinkhani
  • 318
  • 4
  • 15
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
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.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121