Chris Chris - 7 months ago 73
JSON Question

Is array order preserved when deserializing using

Will the order of the elements in an array property be maintained when I deserialize a json object to a c# object using then library? For example:

public class MySonsThreeFootRadius
public Boolean IsMessy { get; set; }
public Toy[] ToysThrownOnFloor { get; set; }

public class Toy
public String Name { get; set; }

"IsMessy": true,
"ToysThrownOnFloor": [
{ "Name": "Giraffe" },
{ "Name": "Ball" },
{ "Name": "Dad's phone" }

Does ToysThrownOnFloor retain the order Giraffe, Ball, and Dad's phone, or could it potentially be reordered?


It depends on what collection you're using.

Any class implementing IEnumerable/IEnumerable<T> can be serialized as a JSON array. Json.NET processes collection sequentally, that is, it will serialize array items in the order the collection returns them from GetEnumerator and will add items to the collection in the order they're deserialized from JSON file (using either Add method in case of mutable collections, and constructor with collection argument in case of immutable collections).

That means that if the collection preserves the order of items (T[], List<T>, Collection<T>, ReadOnlyCollection<T> etc.), the order will be preserved when serializing and deserializing. However, if a collection doesn't preserve the order of items (HashSet<T> etc.), the order will be lost.

The same logic applies to JSON objects. For example, the order will be lost when serializing Dictionary<TKey, TValue>, because this collection doesn't preserve the order of items.