Reputation: 57
I'm trying to create a custom collection converter in json.net that serializes a collection or list into the following format:
Expected JSON Format:
{
"otherProperties": "other",
"fooCollection[0].prop1": "bar",
"fooCollection[0].prop2": "bar",
"fooCollection[1].prop1": "bar",
"fooCollection[1].prop2": "bar"
}
However my custom converter below keeps outputting it like so (will fail, this is not valid json):
Actual JSON Format:
{
"otherProperties": "other",
"fooCollection" :
"fooCollection[0].prop1": "bar",
"fooCollection[0].prop2": "bar",
"fooCollection[1].prop1": "bar",
"fooCollection[1].prop2": "bar"
}
My Custom Converter snippet:
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;}
}
How can i omit the list property name from being serialized? Thanks!
Upvotes: 0
Views: 245
Reputation: 129687
You can't exclude or change a parent property name from within a child object's converter. By the time the child converter is called, the parent property name has already been written to the JSON. If you're trying to "flatten" your hierarchy such that a child object's properties appear as properties within the parent, you need to make the converter work for the parent object.
In other words:
[JsonConverter(typeof(FooClassDtoConverter))]
public class FooClassDto
{
int OtherProperties {get;set;}
List<T> FooCollection {get;set;}
}
Then inside your WriteJson method...
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();
Upvotes: 1