-2

when I was learning Newtonsoft JSON I used the following to serialize an object:

public сlass Foo 
{
    public Bar Bar { get; set; }
}

public class Bar 
{
    public string Title { get; set; }
}

var foo = new Foo();
JsonConvert.SerializeObject(foo, Formatting.Indented);

The result is { "Bar": null } but I would like to print { "Bar": { "Title": null } } without creating an instance of Bar.

I used the solution of ServiceStack (the Dump method) and returned an empty object. Maybe overload a method in the DefaultContractResolver?

SilentStorm
  • 172
  • 1
  • 1
  • 12
Edwok
  • 3
  • 3

1 Answers1

1

how do I get the JSON of { "Bar": { "Title": null } } without creating instance a Bar.

You can't unless you start handcrafting your Json. If you do not create an instance of Bar, Bar will always return null.

You could create an instance of Bar and set the title to null, this way should work, but that wasn't the question.

SilentStorm
  • 172
  • 1
  • 1
  • 12
  • Yes, you are right, but the question isn't about it. It's possible to do this from DefaultContractResolver or JsonConvert? – Edwok Nov 29 '16 at 10:20
  • You could: make a custom class, inherit from DefaultContractResolver and override your Json (handcrafting imho). Examples can be found [here](http://www.newtonsoft.com/json/help/html/contractresolver.htm). Easiest solution is still like @HebeleHododo mentioned: Initialize Bar in Foo's constructor. – SilentStorm Nov 29 '16 at 10:26