Json.net 自定义集合转换器

Json.net custom collection converter

我正在尝试在 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;}
}

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

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

换句话说:

[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();