Json.net deserializing list gives duplicate items

前端 未结 4 1414
眼角桃花
眼角桃花 2021-02-18 15:56

I have just started using Newtonsoft.Json (Json.net). In my first simple test, I ran into a problem when deserializing generic lists. In my code sample below I serialize an obje

4条回答
  •  耶瑟儿~
    2021-02-18 17:01

    That is because you are adding items in the constructor. A common approach in deserializers when processing a list is basically:

    • read the list via the getter
      • if the list is null: create a new list and assign via the property setter, if one
    • deserialize each item in turn, and append (Add) to the list

    this is because most list members don't have setters, i.e.

    public List Items {get {...}} // <=== no set
    

    Contrast to arrays, which must have a setter to be useful; hence the approach is usually:

    • deserialize each item in turn, and append (Add) to a temporary list
    • convert the list to an array (ToArray), and assign via the setter

    Some serializers give you options to control this behavior (others don't); and some serializers give you the ability to bypass the constructor completely (others don't).

提交回复
热议问题