0

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.

  • You need to a custom to converter to `MyClass` not `MyNestedClass`. [Can I serialize nested properties to my class in one operation with Json.net?](https://stackoverflow.com/q/30175911/3744182) is one example. In fact this may be a duplicate, agree? – dbc Feb 23 '21 at 23:16
  • Incidentally [`CustomCreationConverter`](https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs#L99) is not a useful class for you to inherit from because is designed for customization of **object construction**. As such it overrides `CanWrite => false;` which is why your `WriteJson()` is never called. – dbc Feb 23 '21 at 23:20
  • Thanks for the answers. @dbc indeed that was the problem why ```WriteJson``` was never called. I override the ```CanWrite``` prop getter to return true instead of false, now ```WriteJson``` is called. (I used ```CustomCreationConverter``` because I already override the ```Create``` method (due to I use interface as reference type and not the concrete class) – user2369698 Feb 23 '21 at 23:46

0 Answers0