【问题标题】:C# JsonConvertDeserialization returning null valuesC# JsonConvertDeserialization 返回空值
【发布时间】:2015-12-20 13:22:34
【问题描述】:

我试图了解为什么我会得到以下内容的空值:

json:

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

类:

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

    public string LookupDelayInMillis { get; set; }
}

调用:

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

类已实例化,但 IdentityTtlInSeconds 和 LookupDelayInMillis 的值为 null。我不明白为什么他们应该是

【问题讨论】:

  • 反序列化为动态而不是你的类。查看它反序列化的内容并确保您的类是这样的。

标签: c# json json.net deserialization


【解决方案1】:

您还需要一个类 - 一个具有一个名为 IdentityService 的属性的对象:

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

您需要这个类,因为您拥有的 JSON 有一个名为 IdentityService 的属性,而此对象有两个属性,分别名为 IdentityTtlInSecondsLookupDelayInMillis。如果您使用的是默认序列化程序,您的类需要反映您在 JSON 字符串中的结构。

现在您可以使用它来反序列化您的字符串:

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

【讨论】:

  • 或者从json中去掉IdentityService,这样数据就只包含属性,可以直接反序列化成一个IdentityService。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多