我有一个包含附加信息列表的对象。
public class ParentObject
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
public IList<BaseInformation> AdditionalInformation{get;set;}
}
public abstract class AbstractInformation {}
public class ConcreteInformation1 : AbstractInformation
{
public string Concrete1Extra1{ get; set; }
public string Concrete1Extra2{ get; set; }
}
public class ConcreteInformation2 : AbstractInformation
{
public string Concrete2Extra1{ get; set; }
}
我想要一个像这样的json对象
{
"Prop1": "MyValue1", //From ParentObject
"Prop2": "MyValue2", //From ParentObject
"Concrete1Extra1" : "Extra1" // From ConcreteInformation1
"Concrete1Extra2" : "Extra2" // From ConcreteInformation1
"Concrete2Extra1" : "Extra3" // From ConcreteInformation2
}
我知道我的目标看起来很容易出错(列表中有两个ConcreteInformation1对象会导致属性名称重复),但我简化了我的问题和示例,以便只专注于找到将列表作为属性组合到父对象中的解决方案。
我曾尝试编写我自己的JsonConverter,但在o.AddBeforeSelf()
上出现错误,因为JObject.PParent为null。
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
o.AddBeforeSelf(new JProperty("PropertyOnParent", "Just a test"));
o.WriteTo(writer);
}
}
尝试将WriteJson
方法更改为如下所示:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null || !(value is ParentObject))
return;
var pObject = (ParentObject) value;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(pObject.Prop1);
writer.WritePropertyName("Prop2");
writer.WriteValue(pObject.Prop2);
foreach (var info in pObject.AdditionalInformation)
{
JObject jObj = JObject.FromObject(info);
foreach (var property in jObj.Properties())
{
writer.WritePropertyName(property.Name);
writer.WriteValue(property.Value);
}
}
writer.WriteEndObject();
}
但正如您所说,当集合中有多个来自同一类型的对象时要小心。它将在json字符串中生成多个具有相同属性名称的属性,并且在反序列化过程中会出现问题。