3

For example, if I deserialize the following JSON into a JsonNode:

{
   "property1": 1,
   "property2": 2,
   "property3": 3
}

and then traverse the elements with JsonNode#fields, is there any guarantee that the iterator will return the properties in the order they were defined (i.e. property1, property2, property3)?

Intuitively I would assume the answer is no, because the JSON spec defines objects as "an unordered set of name/value pairs". HOWEVER, JSON RFC (RFC 7159) says this:

JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software.

And I haven't been able to find any information about how Jackson handles this.

Community
  • 1
  • 1
mark.monteiro
  • 2,609
  • 2
  • 33
  • 38

1 Answers1

3

looking at the source code of Jackson's com.fasterxml.jackson.databind.node.ObjectNode (version 2.5.0, you can search on the site for a different one), the map which holds the object's children is of type LinkedHashMap where the documentation says

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
  • 2
    This is a start but doesn't really answer the question. With this knowledge I guess my question then becomes, "Does Jackson guarentee in-order insertion of properties into its LinkedHashMap when deserializing?" – mark.monteiro Apr 10 '17 at 14:30
  • I don't see why Jackson dev would choose such an implementation for any other reason – Sharon Ben Asher Apr 11 '17 at 05:58
  • 1
    While it wouldn't make any sense to use a `LinkedHashMap` and not implement strict property ordering, having it explicitly guaranteed by Jackson would be nice. When you have a key business algorithm depending on field order, knowing that Jackson asserts and maintains ordering is more solid justification than a hunch and empirical evidence of the *current* implementation. – Gordon Bean Aug 04 '21 at 15:40