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


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01