Ordered Structs in ColdFusion
Last week I was working on a project and wanted to use a ColdFusion struct to push data into XML and JSON. The challenges were a) I wanted the XML and JSON translations to be “dumb”. i.e., I can push a structure to each one, and they translate them automatically and b) I wanted the output to be the same each time and the same across formats. However, if you call structKeyList() the list of structure keys are not ordered, so looping over the keys returns unpredictable results.
The solution was to access CF’s underlying Java. The ColdFusion struct is based on the Java HashMap. An extension of this is the Java LinkedHashMap, which behaves much like (and can be access by CF in the same way) as a HashMap/CF Struct but it keeps an ordered list of the keys.
<cfset structA = structNew() />
<cfset structA.first = “first” />
<cfset structA.second = “second” />
<cfset structA.third = “third” />
<cfloop list=”#structKeyList(structA)#” index=”i”>
<cfset structB = createObject(“java”, “java.util.LinkedHashMap”).init() />
<cfset structB.first = “first” />
<cfset structB.second = “second” />
<cfset structB.third = “third” />
<cfloop list=”#structKeyList(structB)#” index=”i”>
Above we’re creating the similar objects, one of which is a regular CF struct (Java HashMap) and the other a LinkedHasMap. Running this code returns the following:
Hat tip to @raelehman for finding the solution.