Json.Net 反序列化$type object.property 的信息



使用 Json.Net 库序列化对象时。 使用 TypeNameHandling,我们可以将类型信息添加到 JSON 中,例如:

var testJson = @"{                              
'parameters': [
{
'key': 'bool define',
'field': {
'$type': 'SomeCustomType',
'description': 'user defined'
}
}
]
}";

当我尝试将该类型反序列化为对象时:

var customObject = JsonConvert.DeserializeObject<CustomType>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None });
[DataContract]
public class CustomType
{       
[DataMember(Name = "parameters")]
public List<Parameter> Parameters { get; set; }
}
[DataContract]
public class Parameter
{
[DataMember(Name ="key")]
public string Key { get; set; }
[DataMember(Name ="field")]
public UserCustomType Field { get; set; }
}
[DataContract]
public class UserCustomType 
{
[JsonProperty("$type")]
[DataMember(Name = "$type")]
public string Type { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}

当我将该 JSON 字符串反序列化为 CustomType 时,我总是在 UserCustomType.Type 字段中获得 null,但例如描述具有一些值。 是否有可能通过反序列化获得该$type字段?(我知道我们总是可以用户反思,但不知道有没有更简单的解决方案(?

通过将元数据属性处理设置为忽略,然后可以使用 PropertyName 属性序列化/反序列化属性,因为 $ 指示元数据

var customObject = JsonConvert.DeserializeObject<CustomType>(json, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
[JsonProperty("$type")]
public string Type{ get; set; }

您可以将类更改为:

[DataContract]
public class UserCustomType
{
[JsonProperty("type")]
[DataMember(Name = "@type")]
public string @Type { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}

您可以使用以下 json:

var testJson = @"{                              
'parameters': [
{
'key': 'bool define',
'field': {
'type': 'SomeCustomType',
'description': 'user defined'
}
}
]
}";

相关内容

最新更新