I have a class (MyClass), in which there is a reference type field (let's call MyNestedClass). I'm using Newtonsoft, and I would like to serialize this class, including this field. But instead of "opening a new block" in the Json (a Json object), I would like this field to remain in the same level as the other (primitive) fields of this class. It's guaranteed, that the MyNestedClass contains only one field.
public class MyClass
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nested_prop", Required = Required.Always)]
public MyNestedClass NestedProp { get; set; }
...
}
public class MyNestedClass
{
public string Address { get; set; }
}
output (with some values):
{
"name" : "foo_val",
"nested_prop" : {
"Address" : "bar_val" // it gets its name (Address) by default (based on the prop name)
}
}
what I want:
{
"name" : "foo_val",
"address" : "bar_val"
}
(of course I have my reasons why do I need a separate class (MyNestedClass) instead of putting that string (Address) into the MyClass class)
I tried to create a converter (CustomCreationConverter
) with overriding the WriteJson
method, but it never gets called during the serialization process...
================================================
Edit:
I used CustomCreationConverter
because I have already overridden its Create
method (my prop type in my real problem is an interface, and not the concrete class)
As @dbc hinted, WriteJson
hasn't been called because in CustomCreationConverter
the CanWrite
method is overriden with return false
. Overriding also this method in my custom converer solves this problem.