Json反序列化多个类型的属性



我有一个json,看起来可能如下:

{
"description": "my description",
"company": "my company"
}

{
"description": "my description",
"company": {
"name": "my company"
}
}

如何将它们反序列化为如下模型:

public class ResponseModel
{
[JsonProperty("description")]
public string Description {get; set;}
[JsonProperty("company")] // and specify possible list of types as string or CompanyModel
public object Company {get; set;}
}

我认为你应该这样做:

首先为公司属性添加注释,并创建一个辅助模型it

public class ResponseModel
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("company")] // and specify possible list of types as string or CompanyModel
[JsonConverter(typeof(CompanyJsonConverter))] // add this line
public string Company { get; set; }
}
public class CompanyHelperModel
{
public string name { get; set; }
}

然后创建实际的转换器类(遗憾的是,我现在无法测试它,但逻辑应该是正确的(:

public class CompanyJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// don't care
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string)) return reader.ReadAsString();
return JsonConvert.DeserializeObject<CompanyHelperModel>(reader.ReadAsString()).name;
}
public override bool CanConvert(Type objectType)
{
return true;
}
}

就这样!我以为你只需要读它,而不需要写它

我通常使用JsonConstructor

public class ResponseModel
{
[JsonProperty("description")]
public string Description { get; set; }

public Company Company { get; set; }
[JsonConstructor]
public ResponseModel(JToken company)
{
if ( company.Type == JTokenType.String )
Company = new Company { Name = (string) company };
else Company = company.ToObject<Company>();
}
}
public class Company
{
[JsonProperty("name")]
public string Name { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新