c# - System.Text.Json 不能用对象数组反序列化一个对象?

标签 c# json .net deserialization system.text.json

我有一个如下所示的 json 结构:

{
"SystemType": "SingleDevice",
"Devices":
[
    {
    "DeviceSettings":{
        "DeviceType": "Blah",
        "Generates": 4,
        "RAdd": 10,
        "TAdd": 10,
        "Distance": 1,
        "IpAddress": "192.168.0.21",
        "Port": 50002 
        }
    }
]}

然后我有两个看起来像这样的类:

DeviceSettings.cs

public class DeviceSettings
{
    public string DeviceType { get; set; }
    public int Generates { get; set; }
    public double RAdd{ get; set; }
    public double TAdd { get; set; }
    public double Distance { get; set; }
    public string IpAddress { get; set; }
    public int Port { get; set; }
}

系统设置.cs

  public class SystemSettings
{
    public string SystemType { get; set; }
    public DeviceSettings[] Devices { get; set; }
}

当我调试以下代码并查看局部变量时,返回的结果对象存在但存在一些问题。 SystemType 正确显示“SingleDevice”,Devices 表示它是一个大小为 1 的数组,并提供元素 0,但是当我查看所有内容的实际值时,它们要么为 null 要么为 0。具体来说,DeviceType 和 IpAddress = null,所有内容else 为 0。谁能解释为什么以及如何解决这个问题?

        static void Main(string[] args)
    {
        var configFilePath = @"C:\Users\Public\Documents\myFolder\SystemConfiguration.json";
        var config = System.IO.File.ReadAllText(configFilePath);
        Console.WriteLine(config);
        var systemSettings = JsonSerializer.Deserialize<SystemSettings>(config);
        Console.ReadKey();
    }

locals output

我看过讨论推断类型的帖子,但我相信这里的一切都是明确的。我不太确定发生了什么。

最佳答案

您缺少一个对象来保存 DeviceSettings 属性:

public class SystemSettings
{
    public string SystemType { get; set; }
    public Device[] Devices { get; set; } // <-- change this
}

// Add this
public class Device
{
    public DeviceSettings DeviceSettings { get; set; }

}

public class DeviceSettings
{
    //snip
}

关于c# - System.Text.Json 不能用对象数组反序列化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69074187/

相关文章:

c# - 如何使用 LINQ 将数组对象转换为另一个对象?

C# 自定义项目模板

c# - 我应该调用 SaveChanges 一次还是在每次更改后调用?

c# - 在 c# 中将文档保存在 mongodb 中时排除字段

c# - 需要使用 LINQ 从多维数组中求和

javascript - 将对象组合成新对象作为 json 用于 web api 请求的发布

javascript - 使用 Javascript 或 jQuery 在 JSON(外部本地文件)中插入/更新新记录

java - 如何使用 jackson objectmapper 反序列化

c# - 在 ConfigureServices 中注册服务时会调用哪个构造函数

c# - 部署后无法加载文件或程序集