Json.net自定义集合转换器

时间:2016-04-26 15:54:35

标签: c# json.net

我试图在json.net中创建一个自定义集合转换器,将集合或列表序列化为以下格式:

预期的JSON格式:

   { 
       "otherProperties": "other",
       "fooCollection[0].prop1": "bar",
       "fooCollection[0].prop2": "bar",
       "fooCollection[1].prop1": "bar",
       "fooCollection[1].prop2": "bar"
   }

但是我的自定义转换器会像这样输出它(会失败,这不是有效的json):

实际JSON格式:

{
   "otherProperties": "other",
   "fooCollection" : 
        "fooCollection[0].prop1": "bar",
        "fooCollection[0].prop2": "bar",
        "fooCollection[1].prop1": "bar",
        "fooCollection[1].prop2": "bar"
}

我的自定义转换器代码段

var fooList = value as List<T>;

var index = 0;

foreach (var foo in fooList)
{
    var properties = typeof(T).GetProperties();
    foreach (var propertyInfo in properties)
    {
        var stringName = $"fooCollection[{index}].{propertyInfo.Name}";
        writer.WritePropertyName(stringName);
        serializer.Serialize(writer, propertyInfo.GetValue(foo, null));
     }

     index++;
}


public class FooClassDto
{
   int OtherProperties {get;set;}

   [JsonConverter(typeof(MyCustomConverter))]
   List<T> FooCollection FooCollection {get;set;}
}

如何省略列表属性名称的序列化?谢谢!

1 个答案:

答案 0 :(得分:0)

您不能从子对象的转换器中排除或更改父属性名称。调用子转换器时,父属性名称已写入JSON。如果您尝试“展平”层次结构,使子对象的属性显示为父对象中的属性,则需要使转换器适用于对象。

换句话说:

[JsonConverter(typeof(FooClassDtoConverter))]
public class FooClassDto
{
   int OtherProperties {get;set;}
   List<T> FooCollection {get;set;}
}

然后在你的WriteJson方法中......

var foo = (FooClassDto)value;

writer.WriteStartObject();
writer.WritePropertyName("OtherProperties");
writer.WriteValue(foo.OtherProperties);

var index = 0;

foreach (var item in foo.FooCollection)
{
    var properties = typeof(T).GetProperties();
    foreach (var propertyInfo in properties)
    {
        var stringName = $"fooCollection[{index}].{propertyInfo.Name}";
        writer.WritePropertyName(stringName);
        serializer.Serialize(writer, propertyInfo.GetValue(item, null));
     }

     index++;
}

writer.WriteEndObject();