Is array order maintained during deserialization using json.net?

Will element ordering in an array property be maintained when I deserialize a json object for a C # object using the json.net library? For instance:

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 phone" } ] } 

Does ToysThrownOnFloor keep the Giraffe, Ball, and Dad phone order, or can it be reordered?

+6
source share
2 answers

It depends on which collection you use.

Any class that implements IEnumerable / IEnumerable<T> can be serialized as a JSON array. Json.NET sequentially processes the collections, i.e. serializes the elements of the array in the order in which the collection returns them from GetEnumerator , and adds the elements to the collection in the order in which they are deserialized from the JSON file (using the Add method in the case of mutable collections and the constructor with the collection argument in the case of immutable collections).

This means that if the collection preserves the order of elements ( T[] , List<T> , Collection<T> , ReadOnlyCollection<T> , etc.), the order will be preserved during serialization and deserialization. However, if the collection does not preserve the order of elements ( HashSet<T> , etc.), the Order will be lost.

The same applies to JSON objects. For example, the order will be lost when serializing Dictionary<TKey, TValue> , because this collection does not preserve the order of elements.

+9
source

The json spec does not indicate that the order should be kept, but it says:

The array structure is a pair of square bracket markers surrounding zero or more values. Values ​​are separated by commas. The order of magnitude is significant.

The specification also states:

JSON also provides support for ordered lists of values. All programming languages ​​will have some function to represent lists that can be executed by name, such as an array, vector, or list.

And from the json.net documentation , the deserialization example certainly refers to the stored order:

 string json = @"[ { 'Name': 'Product 1', 'ExpiryDate': '2000-12-29T00:00Z', 'Price': 99.95, 'Sizes': null }, { 'Name': 'Product 2', 'ExpiryDate': '2009-07-31T00:00Z', 'Price': 12.50, 'Sizes': null } ]"; List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json); Console.WriteLine(products.Count); // 2 Product p1 = products[0]; Console.WriteLine(p1.Name); // Product 1 

Based on the specs and documentation of json.net, it would be safe to assume that the order is preserved.

+3
source

Source: https://habr.com/ru/post/975596/


All Articles