[英].NET core 3: Order of serialization for JsonPropertyName (System.Text.Json.Serialization)
[英]System.Text.Json.Serialization Does not appear to work for JSON with NESTED classes
如何定義僅使用 System.Text.Json.Serialization 工作的 class?
使用 Microsoft 的 Newtonsoft 反序列化的新替代方法目前不適用於嵌套類,因為在反序列化 JSON 文件時,所有屬性都設置為 null。 使用 Newtosonsoft 的 Json 屬性屬性[JsonProperty("Property1")]
維護屬性的值。
謝謝!
public class Class1
{
[JsonProperty("Property1")]
public string Property1 { get; set; }
}
使用 Visual Studio 的粘貼 JSON 粘貼到 class 以創建 class:
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; }
}
問題是使用 System.Text.Json.Serialization時,嵌套類的屬性設置為 null。
{
"property1": null
}
使用 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
混合。 那是行不通的。
System.Text.Json
中的等效屬性是[JsonPropertyName]
。
您還需要匹配大小寫(對於System.Text.Json
,這就是屬性被評估為 null 的原因)。 從您引用的文檔中:
默認情況下,屬性名稱匹配區分大小寫。 您可以指定不區分大小寫。
因此,如果您的 json 屬性如下所示:
{
"property1": "abc"
}
然后,您的 class 應該如下所示:
public class Class1
{
[JsonPropertyName("property1")]
public string Property1 { get; set; }
}
請注意,“property1”在JsonPropertyName
屬性中是小寫的。
查看此在線演示。
要指定不區分大小寫,您可以在序列化程序選項中使用PropertyNameCaseInsensitive
:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
var data = JsonSerializer.Deserialize<Root>(json, options);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.