我正在编写第一个 ORM 支持的 REST api,但在 JSON 序列化方面遇到了一些问题。这是我的实体定义之一:
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;
}
}
这是它扩展的基础实体(用于 super.getMemento 等):
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;
}
}
这个扩展的类与这里无关。
最后,这是呈现数据的 json 表示形式的代码的简化版本:
<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;
}
您可以在第二个代码片段的 getMemento()
实现中看到,我尝试通过 javacasting 所有 ID 属性的值来解决此问题(每个实体都有一个名为“id”的属性) ) 为整数。这是行不通的。我也尝试过 javacast("int", local.memento.id * 1); ,但这也不起作用。
无论我尝试什么,生成的 json 看起来都是这样的:
[{"termB":"2","termA":"1","id":"1","relationship":"+"},{"termB":"4","termA":"1","id":"3","relationship":"-"}]
我期待的是:
[{"termB":"2","termA":"1","id":1,"relationship":"+"},{"termB":"4","termA":"1","id":3,"relationship":"-"}]
我迷茫了。我缺少什么?为什么这不起作用?
最佳答案
这是Adobe对serializeJSON所做的改变吗?
http://coldfusion.tcs.de/adobe-please-fix-coldfusion-serializejson/
关于json - 冷融合9 : Using serializeJson on Hibernate entity encodes numeric properties as strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629281/