我有一个基类和派生类,我想自定义派生类的JSON序列化/反序列化,但要在基类中进行序列化/反序列化。我看不到如何用JsonConverter类来做到这一点。
示例类
public class MyBase
{
public long id { get; set; }
public virtual string name { get; set; }
public string desc { get; set; }
...
}
[JsonConverter(typeof(MyDerivedSerializer))]
public class MyDerived : myBase
{
public double rate { get; set; }
public double temp { get; set; }
...
}
public class MyDerivedSerializer : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var baseS = value as MyBase;
//??? How to get JSON for base class
//Add items for derived class
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
while ((reader.TokenType != JsonToken.Null) && (reader.TokenType != JsonToken.EndObject))
{
JObject jo = JObject.Load(reader);
JToken itemProps = jo["properties"];
jo.Remove("properties");
foreach (JToken c in itemProps.Children())
{
if (c.Type == JTokenType.Property)
{
JProperty p = c as JProperty;
if (!jo.ContainsKey(p.Name))
jo[p.Name] = p.Value;
}
}
}
//now that the JSON is good, how do I put the data in a created derived object
var x = Activator.CreateInstance(objectType);
return x;
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
使用JSON的工具需要在名为“ properties”的子字段中的所有派生类属性,但是我无法更改派生类。因此,我只想使用JsonConveter来编辑JSON即可。
{
"id": 33,
"name": "xSource",
"desc": "Main source",
...
"properties": {
"rate": "3.21",
"temp": "245.2"
...
}
}
答案 0 :(得分:1)
您将需要清理一下,但是我把它吐了
{“ id”:1,“ name”:“ Name”,“ desc”:“ Desc”,“ properties”:{“ rate”:2.0,“ temp”:3.0}}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject((MyBase)value);
JObject jo = (JObject)t;
var baseProperties =
typeof(MyBase).GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.DeclaredOnly);
var derivedProperties =
typeof(MyDerived).GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.DeclaredOnly);
var derivedValues = jo.Properties().Where(x => derivedProperties.Any(y => y.Name == x.Name));
var baseValues = jo.Properties().Where(x => baseProperties.Any(y => y.Name == x.Name)).ToList();
JObject o = new JObject(baseValues);
o.Add(new JProperty("properties", new JObject(derivedValues)));
o.WriteTo(writer);
}
必须从类中删除装饰器,然后移到反序列化调用,就像获得stackoverflow一样。
var result = JsonConvert.SerializeObject(test, new KeysJsonConverter());