Will the order of the elements in an array property be maintained when I deserialize a json object to a c# object using then json.net 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?
Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine): An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
The JSON RFC (RFC 4627) says that order of object members does not matter.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.
We can implement JSON Serialization/Deserialization in the following three ways: Using JavaScriptSerializer class. Using DataContractJsonSerializer class. Using JSON.NET library.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With