If you encode your structs or arrays to JSON in ColdFusion 10 you may see some strange and unexpected results happen. The reason is that ColdFusion is a type-less language and don't know anything about the type of a variable. This means all your variables are strings very first. But you need to have valid values for boolean or integers or floats.
ColdFusion cannot do this for you out of the box by today. What ColdFusion does is really stupid and causes a lot of unexpected troubles as CF has no idea about the variable type. It simply tries to find out what type of variable the value may be and converts it to these type. As always with automatism's they must and will fail! The problems you may face are the following:
- A string
NO that is the ISO code of Norway will be converted to
- A string
YES will be converted to
true. Hmmm - FAIL.
- A ZIP code from the UK starting with integers and ending with letters will cause errors. FAIL
- A string that represents a telephone number like
+49173123456789 will end in a string
- All your variable names become UPPERCASE. FAIL
- Other issues like these...
You see this is not desired. Compared to PHP you can cast the type with
(int) $foo or
(float) $foo or
(bool) $foo or with
settype($foo, 'float'). ColdFusion is missing such a function completely. Your are simply lost.
Adobes workaround is bugfix #3803565 that allows you to disable the automatism by adding a server global setting named
-Djson.string.noconversion=true to your jvm.conf. This keeps all your strings as strings, and you totally lose boolean, integers and floats. After testing we decided that his is not what we want and moved on to JsonSerializer.cfc - Data Serialization Utility for ColdFusion. This CFC allows you to define the data type of a variable and convert it to this type properly. It also keeps CamelCase of variable names, too. It's a bit more work to implement, but what is does is the only way how you can solve these data type conversion issues in ColdFusion. The result is a properly encoded JSON string. Please note that there is still a bug with boolean in String values "YES" and "NO" converted to Boolean that I fixed, but is not yet committed. Until today we only found that Ben Nadels CFC solution seems not working with complex and dynamic data. That may be a problem for you.
It is documented that SerializeJSON behavior will change in ColdFusion 11, but have not tested it yet. But it still has limitations and only preserve the data type in Querys and CFCs. This may help a lot and may allow to workaround, but it will not really solve all the issues. I hope ColdFusion will add a settype function in future like PHP already has to solve this finally.