简体   繁体   English

如何将 json 对象反序列化为 C#

[英]How deserialize json object to c#

I want deserialize this object from JSON:我想从 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!请帮帮我吧!

Try with this change.尝试进行此更改。 This way your C# classes will match the JSON object your are receiving.这样您的 C# 类将匹配您正在接收的 JSON 对象。 You should of course extend the Data class to include the rest of the json fields if they are of interest to you.如果您感兴趣,您当然应该扩展Data类以包含其余的 json 字段。

  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 .您会注意到我将所需的AllowNull添加到Expiration + RegistrantEmail并将Data属性添加到Always If you send null for Data the deserialization will fail.如果您为Data发送 null ,反序列化将失败。

  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.此答案还考虑了序列化 json 字符串中的某些字段可能为 null,因此在这种情况下不会抛出异常。

Your class doesn't match the JSON... Here are a couple of classes that do match the JSON:您的课程与 JSON 不匹配...这里有几个与 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.我直接从您的 JSON 在线生成它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM