$json.generate changes object property order

27 views
Skip to first unread message

Dave Hess

unread,
Apr 19, 2023, 10:40:14 AM4/19/23
to dotCMS User Group
I'm generating a list of Software feature using a content pull. For each feature I want to show generate a list of that shows whether than feature exists in that version of the software. The versions are basic, silver, gold and platinum. Those version properties are stored with each software feature using a category named versions. In my velocity code I very specifically add the features in  a specific order, but when I use $json.generate the order is changed. Is there any way to fix this?

#set($versionList = ["basic", "silver", "gold", "platinum"])
#set($itemList = $dotcontent.pullRelatedField($!{ContentIdentifier}, "SoftwareFeatures.items", null, 0, null))
#foreach($item in $itemList)
    #set($itemVersionList = $contents.getEmptyList()) #* Array of versions for each Software Feature *#
    #set($itemVersionListMap = $contents.getEmptyMap()) #* Hashmap of versions for each Software Feature indicating true/false *#
    #foreach($version in $item.versions) #* Get versions from content instance and add them to the array of item versions *#
        #set($tmp = $!itemVersionList.add($!{version.key}))
    #end
    #foreach($prop in $versionList) #* Loop through master version list (which is ordered appropriately) *#
        #if ($itemVersionList.contains(${prop}))
            #set($tmp = $!itemVersionListMap.put($!{prop}, "true")) #* Put version if HashMap with "true" value *#
        #else
            #set($tmp = $!itemVersionListMap.put($!{prop}, "false")) #* Put version if HashMap with "true" value *#
        #end
    #end
#end
itemVersionListMap: $itemVersionListMap
OUTPUT
itemVersionListMap: {gold=true, platinum=true, silver=true, basic=true}

jonathan...@dotcms.com

unread,
Apr 19, 2023, 2:02:21 PM4/19/23
to dotCMS User Group
it is a good question, unfortunately the getEmptyMap() returns a HashMap which the order does not matter.
On Java the Map that keeps the insert order is the LinkedMap



public Map getEmptyLinkMap() {
    return new java.util.LinkedHashMap();
}

on the velocity

$osgitool.getEmptyLinkMap()

It will keep the insert order

In case you are more interested on Alpha-order you can use TreeMap instead.

Best,
J
Reply all
Reply to author
Forward
0 new messages