gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:38:07 24 4
gpt4 key购买 nike

我有一个如下所示的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com