Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array order preserved when deserializing using json.net?

Tags:

json

c#

json.net

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?

like image 959
Chris Avatar asked Sep 21 '14 00:09

Chris


People also ask

Does JSON preserve array order?

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.

Is Order important in JSON?

The JSON RFC (RFC 4627) says that order of object members does not matter.

What is the difference between serialize and deserialize JSON?

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.

Which of the following options represent the class used to perform JSON serialization in net?

We can implement JSON Serialization/Deserialization in the following three ways: Using JavaScriptSerializer class. Using DataContractJsonSerializer class. Using JSON.NET library.


1 Answers

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.

like image 143
Athari Avatar answered Oct 04 '22 01:10

Athari