我有以下课程:
public class MyRequest
{
public string Type {get;set;}
public string Source {get;set;}
}
我想序列化/反序列化以下值Source
来自名为值的 JSON 字段Type
, 例如:
{
"type": "bank",
"bank": "Some value"
}
or
{
"type": "card",
"card": "Some value"
}
两者都绑定到Source
财产。
您可以创建一个自定义JsonConverter https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm处理动态属性名称:
public class MyRequestConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyRequest);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
string type = (string)jo["type"];
MyRequest req = new MyRequest
{
Type = type,
Source = (string)jo[type ?? ""]
};
return req;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
MyRequest req = (MyRequest)value;
JObject jo = new JObject(
new JProperty("type", req.Type),
new JProperty(req.Type, req.Source));
jo.WriteTo(writer);
}
}
要使用转换器,请添加[JsonConverter]
像这样属性到你的类:
[JsonConverter(typeof(MyRequestConverter))]
public class MyRequest
{
public string Type { get; set; }
public string Source { get; set; }
}
这是一个有效的往返演示:https://dotnetfiddle.net/o7NDTV https://dotnetfiddle.net/o7NDTV
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)