Common Pitfalls

kevin-montrose edited this page Dec 17, 2014 · 1 revision

Jil can be more difficult to use than other JSON libraries due to it's focus on speed, rather than flexibility or ease of use, above all else. This page documents some common pitfalls that are encountered when using Jil.

Missing Members When Serializing

There are two common cases in which Jil will not serialize members where other libraries do.

Inherited Members

If you have a class FooBase and a class Bar : FooBase and a call like JSON.Serialize<Bar>(myBar), Jil will not serialize members inherited from FooBase by default. Note that in many cases the <Bar> generic parameter can be inferred.

To fix this, pass an Options object with ShouldIncludeInherited set to true.

Base Classes As Member Types

If you have a class Foo with a member object Bar {get;}, serializing a Foo instances will only ever produce null or {} for the Bar member even if Foo.Bar is a string, number, and so on. This is due to Jil serializing only what it can determine statically about a type by default, which in Foo's case is that Bar is a System.Object.

To fix this, use JSON.SerializeDynamic() instead of JSON.Serialize<Foo>().

Enums

By default Jil serializes enum types as strings. It will not convert freely between integer representations, instead considering that an error.

The [JilDirective] attribute has a TreatEnumerationAs property which will cause Jil to serialize and deserialize an enum as a integer of the given type. It is still an error to serialize to an integer type too small to contain an enumeration, and an error to deserialize an integer that cannot be mapped to the indicated type.

Strictness

Jil's methods take an optional Options object which is used to configure serialization and deserialization. These options are followed very strictly. By default, Options.Default is assumed.

In particular, Jil will not freely convert between the various DateTimeFormats.

Be sure to always use the appropriate Options object. If you always want a particular Options to always be used, JSON.SetDefault(Options) can be called once to change the Options used if none is explicitly provided.

Heterogeneous Collections

When working with collections of mixed types (ie. new object [] { "foo", 123 }), the JSON.Serialize() and JSON.Deserialize() calls are insufficient. This is because .NET's type system cannot statically represent this.

To work with collections like this, use JSON.SerializeDynamic() and JSON.DeserializeDynamic().

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.