使用json.net反序列化时是否保留数组顺序? [英] Is array order preserved when deserializing using json.net?

查看:184
本文介绍了使用json.net反序列化时是否保留数组顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用json.net库将json对象反序列化为c#对象时,将保持array属性中元素的顺序吗?例如:

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

ToysThrownOnFloor是否保留长颈鹿,鲍尔和爸爸的电话的订单,还是可以重新订购?

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.

任何实现IEnumerable/IEnumerable<T>的类都可以序列化为JSON数组. Json.NET是按顺序处理集合的,也就是说,它将按照集合从GetEnumerator返回它们的顺序序列化数组项,并将按照从JSON文件反序列化的顺序将项添加到集合中(使用Add方法对于可变集合,对于不可变集合,构造函数带有collection参数.

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).

这意味着,如果集合保留项的顺序(T[]List<T>Collection<T>ReadOnlyCollection<T>等),则在序列化和反序列化时将保留该顺序.但是,如果集合不保留项目顺序(HashSet<T>等),则该顺序将丢失.

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.

相同的逻辑适用于JSON对象.例如,序列化Dictionary<TKey, TValue>时,该顺序将丢失,因为此集合不会保留项目的顺序.

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.

这篇关于使用json.net反序列化时是否保留数组顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆