I’m writing my first ORM-backed REST api, and having some issues with the JSON serialization. Here’s one of my entity definitions:
component persistent="true" extends="Base" {
property name="id"
fieldtype="id"
generator="native"
ormtype="int"
type="numeric";
property name="relationship"
type="string"
ormtype="string";
property name="comment"
type="string"
ormtype="text";
//related entities
property name="termA"
cfc="term"
fieldtype="many-to-one"
fkcolumn="termA"
lazy="false";
property name="termB"
cfc="term"
fieldtype="many-to-one"
fkcolumn="termB"
lazy="false";
//override getMemento to include appropriate relationships
public struct function getMemento(){
//standard stuff
local.memento = super.getMemento();
//custom add-ons
local.memento["termA"] = this.getTermA().getId();
local.memento["termB"] = this.getTermB().getId();
return local.memento;
}
}
This is the Base entity it extends (for super.getMemento among other things):
component extends="core.v1.models.Base" {
public struct function getMemento(){
local.memento = deserializeJson(serializeJson(this));
//fix numerics showing up as strings
if (structKeyExists(local.memento, "id")){
local.memento.id = javacast("int", local.memento.id);
}
return local.memento;
}
public array function transformCollectionIntoMementos(array input){
if (arrayLen(arguments.input) > 0){
for (var i = 1; i <= arrayLen(arguments.input); i++){
arraySet(arguments.input,i,i,arguments.input[i].getMemento());
}
}
return arguments.input;
}
}
The class that this one extends isn’t relevant here.
Finally, here’s a simplified version of the code that renders the json representation of the data:
<cfoutput>#serializeJson(transform(entityLoad("interaction")))#</cfoutput>
public array function transform(array input){
if (arrayLen(arguments.input) > 0){
for (var i = 1; i <= arrayLen(arguments.input); i++){
arraySet(arguments.input,i,i,arguments.input[i].getMemento());
}
}
return arguments.input;
}
You can see in the getMemento() implementation in the 2nd code snippet that I’m attempting to resolve this by javacasting the value of all ID properties (each entity has a property named “id”) to an integer. This doesn’t work. I’ve also tried javacast("int", local.memento.id * 1); and that doesn’t work either.
No matter what I’ve tried, the resulting json looks like this:
[{"termB":"2","termA":"1","id":"1","relationship":"+"},{"termB":"4","termA":"1","id":"3","relationship":"-"}]
What I’m expecting is this:
[{"termB":"2","termA":"1","id":1,"relationship":"+"},{"termB":"4","termA":"1","id":3,"relationship":"-"}]
I’m at a loss. What am I missing? Why doesn’t this work?
Is it the change that Adobe made to serializeJSON?
http://coldfusion.tcs.de/adobe-please-fix-coldfusion-serializejson/