System.Text.Json.Serialization Does not appear to work for JSON with NESTED classes(System.Text.Json.Serialization似乎不适用于具有嵌套类的JSON)
问题描述
如何定义仅使用System.Text.Json.Serialization工作的类?
使用Microsoft新的Newtonsoft反序列化替代方案目前不适用于嵌套类,因为在反序列化JSON文件时,所有属性都设置为空。使用Newtosonsoft的Json属性属性[JsonProperty("Property1")]维护属性的值。
谢谢!
public class Class1
{
[JsonProperty("Property1")]
public string Property1 { get; set; }
}
使用Visual Studio的粘贴JSON将JSON粘贴到类以创建类:
public class Rootobject
{
public string Database { get; set; }
public Configuration Configuration { get; set; }
}
public class Configuration
{
public Class1 Class1 { get; set; }
public Class2 Class2 { get; set; }
public Class3 Class3 { get; set; }
}
public class Class1
{
public string Property1 { get; set; }
}
public class Class2
{
public string Property2 { get; set; }
}
public class Class3
{
public string Property3 { get; set; }
}
问题是using System.Text.Json.Serialization嵌套类的属性设置为空时。
{
"property1": null
}
csharp2json
使用Newtonsoft反序列化程序与[JsonProperty("Configuration")]
public class Class1
{
[JsonProperty("Property1")]
public string Property1 { get; set; }
}
public class Class2
{
[JsonProperty("Property2")]
public string Property2 { get; set; }
}
public class Class3
{
[JsonProperty("Property3")]
public string Property3 { get; set; }
}
public class Configuration
{
[JsonProperty("Class1")]
public Class1 Class1 { get; set; }
[JsonProperty("Class2")]
public Class2 Class2 { get; set; }
[JsonProperty("Class3")]
public Class3 Class3 { get; set; }
}
public class RootObject
{
[JsonProperty("Database")]
public string Database { get; set; }
[JsonProperty("Configuration")]
public Configuration Configuration { get; set; }
}
推荐答案
看起来您将Newtonsoft.Json中的[JsonProperty]属性与System.Text.Json中的[JsonProperty]属性混合在一起。那行不通。
System.Text.Json中的等效属性为[JsonPropertyName]。
System.Text.Json,这就是将属性计算为空的原因)。来自您引用的docs:
默认情况下,属性名称匹配区分大小写。您可以指定不区分大小写。
因此,如果您的json属性如下:
{
"property1": "abc"
}
然后,您的类应该如下所示:
public class Class1
{
[JsonPropertyName("property1")]
public string Property1 { get; set; }
}
请注意,JsonPropertyName属性中的";Property1";是小写的。
签出此online demo。
要指定不区分大小写,可以在序列化程序选项中使用PropertyNameCaseInsensitive:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
var data = JsonSerializer.Deserialize<Root>(json, options);
这篇关于System.Text.Json.Serialization似乎不适用于具有嵌套类的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:System.Text.Json.Serialization似乎不适用于具有嵌套类的JSON
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
