【发布时间】:2022-11-19 01:23:42
【问题描述】:
我正在尝试使用 .net 内置函数反序列化一个对象。
让我们看看我试图反序列化的数组“属性”:
"attributes": [
{
"trait_type": "Subseries",
"value": "Templar Order"
},
{
"trait_type": "Colorfulness",
"value": 2,
"min_value": 1,
"max_value": 5
},
{
"trait_type": "Style",
"value": "CGI"
},
{
"trait_type": "Material",
"value": "Steel"
},
{
"trait_type": "Special Effects",
"value": "Rare"
},
{
"trait_type": "Background",
"value": "Rare"
}],
如您所见,一个属性总是有一个 trait_type 和一个值。
value 可以是 string 或 int 类型。
最小值和最大值是可选的,并且始终是 int 类型。
我正在努力解决的是“价值”领域。我试图从中创建一个类,但 json 反序列化器不会将一个 int 转换为一个字符串(我会很好)
public class MetadataAttribute
{
public MetadataAttribute(string Trait_Type, string Value)
{
trait_type = Trait_Type;
value = Value;
}
public MetadataAttribute(string Trait_Type, int Value, int? Min_Value = null, int? Max_Value = null)
{
trait_type = Trait_Type;
value = Value.ToString();
min_value = Min_Value;
max_value = Max_Value;
}
public MetadataAttribute() { }
/// <summary>
/// the attribute name, eg sharpness
/// </summary>
public string trait_type { get; set; }
/// <summary>
/// the value of the attribute, eg 10
/// </summary>
public string value { get; set; }
/// <summary>
/// optional: the minimum value atribute to provide a possible range
/// </summary>
public int? min_value{get;set;}
/// <summary>
/// optional: the maximum value attribute to provide a possible range
/// </summary>
public int? max_value { get; set; }
}
当前的反序列化函数(当值中没有 int 时有效)
public static Metadata Load(string path)
{
FileInfo testFile = new FileInfo(path);
string text = File.ReadAllText(testFile.FullName);
Metadata json = JsonSerializer.Deserialize<Metadata>(text);
return json;
}
我该如何解决这种歧义?
【问题讨论】:
-
您能否将 C#
value属性的类型更改为其他类型,例如object? -
您需要定义单一数据模型吗?或者你能定义两个吗?
-
复制 app.quicktype.io 中的 Json,包装成
{ },并删除最后一个逗号。如果每种特征类型都应该成为一种类型,那么您可以拥有更具体的东西 -
如果转换字符串没问题,您可以有一个自定义属性来处理反序列化部分的值,并始终从该值生成字符串。
-
@PeterCsala 我可以定义 2 个数据模型,但我不知道如何将它集成到我的 C# 代码中
标签: c# json .net serialization system.text.json