使用 Json.NET 自定义反序列化 [英] Custom Deserialization using Json.NET
问题描述
我有一堂课
public class Order
{
public int Id { get; set; }
public string ShippingMethod { get; set; }
}
并且我想将下面的 JSON 数据反序列化为上面的类/对象
and I want to deserialize a JSON data below into the above class/object
string json = @"{
'Id': 1,
'ShippingMethod': {
'Code': 'external_DHLExpressWorldwide',
'Description': 'DHL ILS Express Worldwide'
}
}";
我的想法是 JSON 中的 ShippingMethod
是一个对象,但我只想获取将传递给 ShippingMethod 的
在反序列化过程中作为 ShippingMethod.Code
(在 JSON 中)Order
类中的 string
.
My idea is that ShippingMethod
in JSON is a object, but I just want to get to ShippingMethod.Code
(in JSON) that will pass into ShippingMethod
as string
in Order
class during deserialization.
如何使用 Json.NET 实现该目标?
how can I accomplish that goal using Json.NET?
我相信我可以使用 CustomJsonConverter 来完成它.但我很困惑.文档中的示例仅适用于 WriteJson
,而不适用于 ReadJson
.
I believe I can accomlish it using CustomJsonConverter. But I get confused. The example in the docs just for WriteJson
, but not ReadJson
.
推荐答案
我只是使用 JsonConverter
正如我上面在我的问题中提到的.在我的完整代码下方:
I just resolve my problem using JsonConverter
as I mentioned above in my question. Below my complete code:
public class Order
{
public int Id { get; set; }
[JsonConverter(typeof(ShippingMethodConverter))]
public string ShippingMethod { get; set; }
}
public class ShippingMethodConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("Not implemented yet");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return string.Empty;
}
else if (reader.TokenType == JsonToken.String)
{
return serializer.Deserialize(reader, objectType);
}
else
{
JObject obj = JObject.Load(reader);
if (obj["Code"] != null)
return obj["Code"].ToString();
else
return serializer.Deserialize(reader, objectType);
}
}
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return false;
}
}
这篇关于使用 Json.NET 自定义反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!