我有一个包含附加信息列表的对象。JSON.NET序列化列表作为父对象的属性
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; }
}
我想有这样的
{
"Prop1": "MyValue1", //From ParentObject
"Prop2": "MyValue2", //From ParentObject
"Concrete1Extra1" : "Extra1" // From ConcreteInformation1
"Concrete1Extra2" : "Extra2" // From ConcreteInformation1
"Concrete2Extra1" : "Extra3" // From ConcreteInformation2
}
我知道我的目标看起来很容易出错(有两个名单中ConcreteInformation1对象将导致重复属性名称)的JSON对象,但我simpified我的问题和示例,以便只关注找到将列表作为属性组合到父对象中的解决方案。
我试图写我自己的JsonConverter,但这是o.AddBeforeSelf()
错误,因为JObject.Parent为空。
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);
}
}
如果您将列表更改为'Dictionary',您可以使用'[JsonExtensionData]'属性获得想要的结果。请参阅此[问题](http://stackoverflow.com/q/14893614/10263)和[答案](http://stackoverflow.com/a/23786127/10263)。 –
2014-09-03 18:58:56