JSON.NET序列化列表作为父对象的属性

时间:2014-09-03 16:11:26

标签: c# json serialization 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; }
}

我希望有一个像这样的json对象

{
    "Prop1": "MyValue1", //From ParentObject
    "Prop2": "MyValue2", //From ParentObject
    "Concrete1Extra1" : "Extra1" // From ConcreteInformation1
    "Concrete1Extra2" : "Extra2" // From ConcreteInformation1
    "Concrete2Extra1" : "Extra3" // From ConcreteInformation2
}

我知道我的目标看起来非常容易出错(在列表中有两个ConcreteInformation1对象会导致重复的属性名称)但我简化了我的问题和示例,以便只关注寻找将列表作为属性组合到父级中的解决方案对象

我曾尝试编写自己的JsonConverter,但由于JObject.Parent为null,因此在o.AddBeforeSelf()上发出错误。

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);
    }
}

1 个答案:

答案 0 :(得分:1)

尝试将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字符串中生成具有相同属性名称的多个属性,并且在反序列化期间您会遇到问题。