7

I'm using Newtonsoft.Json.JsonConvert to serialize a Textbox (WinForms) into json and I want the serialization to skip properties with default values or empty arrays.

I'v tried to use NullValueHandling = NullValueHandling.Ignore in JsonSerializerSettings but is doesn't seem to affect anything.

Here is the full code sample (simplified):

JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.None,
                    DefaultValueHandling = DefaultValueHandling.Ignore,
                    NullValueHandling = NullValueHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace,
                    PreserveReferencesHandling = PreserveReferencesHandling.None,
                    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                };

    string json = JsonConvert.SerializeObject(textbox, settings);

Any ideas ?

Gil Stal
  • 3,354
  • 4
  • 29
  • 32
  • Can I check? In the title and the start of the question, you ask about **serializing**, but the example shows **deserializing**. Which is it that you are trying to do ? – Marc Gravell Jul 24 '12 at 10:08
  • @MarcGravell: Correct, sorry. Copy-pasted the wrong line. – Gil Stal Jul 24 '12 at 10:11

1 Answers1

9

You could use the standard conditional-serialization pattern:

private int bar = 6; // default value of 6
public int Bar { get { return bar;} set { bar = value;}}
public bool ShouldSerializeBar()
{
    return Bar != 6;
}

The key is a public bool ShouldSerialize*() method, where * is the member-name. This pattern is also used by XmlSerializer, protobuf-net, PropertyDescriptor, etc.

This does, of course, mean you need access to the type.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I want to serialize different (winform) controls so this is not an option. – Gil Stal Jul 24 '12 at 10:12
  • @gil in that case you may need to do it all fairly manually, by registering a converter. – Marc Gravell Jul 24 '12 at 12:07
  • Is there anyway I can subclass the regular converter and just add an if to filter out the props I don't want to be serialized? – Gil Stal Jul 24 '12 at 12:19
  • @gil it looks like you'd still have to enumerate the properties yourself for the WriteJson API. For ReadJson you can probably use serializer.Populate. No easy options, I'm afraid.. – Marc Gravell Jul 24 '12 at 13:00