![](/img/trans.png)
[英]JsonSerializer.Deserialize<T>(); in System.Text.Json not deserialize correctly
[英]System.Text.Json can't deserialize an object with an array of objects?
我有一個 json 結構,如下所示:
{
"SystemType": "SingleDevice",
"Devices":
[
{
"DeviceSettings":{
"DeviceType": "Blah",
"Generates": 4,
"RAdd": 10,
"TAdd": 10,
"Distance": 1,
"IpAddress": "192.168.0.21",
"Port": 50002
}
}
]}
然后我有兩個看起來像這樣的類:
設備設置.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; }
}
當我調試以下代碼並查看局部變量時,返回的結果 object 存在但存在一些問題。 SystemType 正確顯示“SingleDevice”,Devices 表示它是一個大小為 1 的數組,並提供元素 0,但是當我查看所有內容的實際值時,它們要么是 null 要么是 0。具體來說,DeviceType 和 IpAddress = null,所有內容否則為 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();
}
我看過討論推斷類型的帖子,但我相信這里的一切都是明確的。 我不太確定發生了什么。
您缺少 object 來保存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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.