C# JsonConvertDeserialization 返回空值

标签 c# json json.net deserialization

我试图理解为什么我得到以下的空值:

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 的值为空。我不明白为什么他们应该是

最佳答案

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

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

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

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

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

关于C# JsonConvertDeserialization 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381422/

相关文章:

c# - 使用 JSON.net 自动序列化 JSON 服务器响应

java - Java 加密与 And .NET 的十六进制生成问题

c# - 如何计算总数使用 c# 的字符串的可能组合?

javascript - 如何访问 JSON 对象中的对象数组?

sql - Azure 数据工厂 - 如何将 SQL 查询结果映射到 JSON 字符串?

json - 实现自定义Newtonsoft JsonConverter(阅读器)

c# - 最灵活的 .NET 规则引擎

c# - 使用正则表达式替换坏词

json - 使用uJson for Delphi解码json

c# - 使用 JsonConvert 反序列化单个 DateTime 对象