System.Text.Json.Serialization似乎不适用于具有嵌套类的JSON [英] System.Text.Json.Serialization Does not appear to work for JSON with NESTED classes

查看:69
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆