0

This is a follow up to this question:

Configure Json.NET serialization settings on a class level

I have a class with properties of other classes

internal class Program
{

    [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public class Foo
    {
        public string Bar;
        public NestedFoo NestedFoo { get; set; }
    }
    public class NestedFoo
    {
        public string NestedBar;
    }

    static void Main(string[] args)
    {

        Foo c = new();
        c.NestedFoo = new();
        c.Bar = "Bar";
        c.NestedFoo.NestedBar = "NestedBar ";
        string output = JsonConvert.SerializeObject(c, Formatting.Indented);

        Console.WriteLine(output);
    }
}

The output result is:

{
  "bar": "Bar",
  "nestedFoo": {
    "NestedBar": "NestedBar "
  }
}

With the above example, the NamingStrategyType apply to the main class members only. The members inside the NestedFoo did not follow the NamingStrategyType

Means NestedBar should be serialized as nestedBar

I know I have the following options, but I prefer to get the intended result using an attribute at the top level class:

  1. apply [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] to the every class inside.
  2. Supply the naming strategy to the JsonConvert.SerializeObject.

Is there any way to have the attribute [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] apply to a top level class and all its nested properties?

Allan Xu
  • 7,998
  • 11
  • 51
  • 122
  • Not directly, no. Json.NET is a contract based serializer, with one contract per type. You want a different contract when one type is serialized inside another, which goes against the basic contract approach. You could make a custom converter that does a recursive serialization using a custom contract resolver. Is that the sort of thing you want? It's a little tricky to do because you need to jump through some hoops to avoid a stack overflow exception as the converter calls itself. – dbc Oct 28 '22 at 19:37
  • Oh, I think I found a duplicate: [JSON .NET Custom Name Resolver for Sub-Properties](https://stackoverflow.com/q/40597532/3744182). Specifically [this answer](https://stackoverflow.com/a/40599731/3744182). Does that answer your question? – dbc Oct 28 '22 at 19:41
  • @dbc, thank you for help. The question was answered 6 years ago. The Newtonsoft improved significantly since then. We should wait a day or two for the community feedback before closing this question. – Allan Xu Oct 28 '22 at 19:53
  • This aspect of Newtonsoft hasn't changed, it's still one contract per type. (But if it has it would be better to add the updated answer to the old question rather than have a new duplicate question with a contradictory answer.) – dbc Oct 28 '22 at 19:58

0 Answers0