C# 自定义Json转换器
我有一个这样的用例,并找到了将json字符串反序列化为C#object的方法 Json数据如下所示,其中C# 自定义Json转换器,c#,json,serialization,C#,Json,Serialization,我有一个这样的用例,并找到了将json字符串反序列化为C#object的方法 Json数据如下所示,其中详细信息属性取决于类型属性 { data: [ { type: "A", detail: { property_a: "plan A" } }, { type: "B", detail: {
详细信息
属性取决于类型
属性
{
data: [
{
type: "A",
detail: {
property_a: "plan A"
}
},
{
type: "B",
detail: {
property_b: "plan B"
}
},
{
type: "A",
detail: {
property_a: "new"
}
}
]
}
C#模型
这个JSON C#在快速浏览时看起来相当。你试过什么?结果如何?你到底在问什么问题?如果我只是简单地使用了
JsonConvert.DeserizalizeObject(jsonString)
,它并没有像预期的那样工作。我希望每个细节属性都是A或B的一个实例。然后我尝试使用CustomCreationConverter,覆盖ReadJson(),但无法使其工作。你们能帮我一个解决方案和可视化代码吗?谢谢。你能解释一下问题出在哪里吗?例如,编辑你的帖子以包含生成的json以及它有什么问题。谢谢你的及时回复。我已经更新了我的帖子,解决了这个问题。谢谢大家!!
public class Results
{
[JsonProperty(PropertyName = "data")]
public List<Result> Data { get; set; }
}
public class Result
{
[JsonProperty(PropertyName = "type"]
public string Type { get; set; }
[JsonProperty(PropertyName = "detail"]
public Detail Detail { get; set; }
}
public class Detail
{
}
public class A: Detail
{
[JsonProperty(PropertyName = "property_a")]
public string PropertyA { get; set; }
}
public class B: Detail
{
[JsonProperty(PropertyName = "property_b")]
public string PropertyB { get; set; }
}
var results = JsonConvert.DeserializeObject<Results>(jsonString);
// results.Data will contains 3 instances of Detail class, not A or B
// therefore, I cannot cast each of them to A or B for usage later.
public class JsonConverter: CustomCreationConverter<Result>
{
public override SearchResult Create(Type objectType)
{
return new Result();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var result = new Result();
// loop through JSON string
while (reader.Read())
{
// return because it is now the end of object
if (reader.TokenType == JsonToken.EndObject)
return result;
if (reader.TokenType != JsonToken.PropertyName)
continue;
var propertyName = reader.Value.ToString();
if (!reader.Read())
return result;
if ("type".Equals(propertyName))
{
result.Type = reader.Value != null ? reader.Value.ToString() : null;
}
else if ("detail".Equals(propertyName))
{
// parse to instantiate A or B
switch (result.Type)
{
case "A":
result.Detail = serializer.Deserialize<A>(reader);
break;
case "B":
result.Detail = serializer.Deserialize<B>(reader);
break;
default:
break;
}
}
}
return result;
}
}
// return because it is now the end of object
if (reader.TokenType == JsonToken.EndObject)
return result;