Is array order preserved when deserializing using json.net?

最后都变了- 提交于 2020-08-02 06:13:05

问题


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?


回答1:


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.




回答2:


The json spec doesn't specifically state that the order should be preserved, rather it says:

An array structure is a pair of square bracket tokens surrounding zero or more values. The values are separated by commas. The order of the values is significant.

The spec also states:

JSON also provides support for ordered lists of values. All programming languages will have some feature for representing such lists, which can go by names like array, vector, or list.

And from the json.net documentation, the deserializing example certainly alludes to the order being preserved:

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 spec and the json.net documentation, it would be safe to assume that the order is preserved.



来源:https://stackoverflow.com/questions/25954701/is-array-order-preserved-when-deserializing-using-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!