android
android

Reputation: 652

ColdFusion doesn't serialize all properties to JSON

When I serialize a component to JSON it only outputs the properties which are set or which have a default value. In my example you can see that the property phone is not getting serialized. Is there any way to change that behaviour in ColdFusion?

User.cfc:

component accessors="true" {
    property name="firstName";
    property name="lastName";
    property name="email" default="";
    property name="phone";
}

Create new user, set properties and serialize to JSON:

var user = new User();
user.setFirstName("Homer");
user.setLastName("Simpson");
writeOutput(serializeJSON(user));

The JSON output:

{"firstName":"Homer","email":"","lastName":"Simpson"}

Upvotes: 1

Views: 612

Answers (2)

Dylan
Dylan

Reputation: 11

Just in case someone else is dealing with this on CF9, the way I solved the issue was by using Jackson (download core, annotations, and databind) from https://mvnrepository.com/artifact/com.fasterxml.jackson.core), then using JavaLoader to mount the JARs:

    <Cfset var paths = []>
    <cfset paths[1] = expandPath("/api/v1/lib/jackson-core-2.0.0.jar")>
    <cfset paths[2] = expandPath("/api/v1/lib/jackson-annotations-2.0.0.jar")>
    <cfset paths[3] = expandPath("/api/v1/lib/jackson-databind-2.0.0.jar")>
    <cfset application.javaloader = createObject("component", "javaloader.JavaLoader").init(paths)>

Then calling Jackson from my CFC:

    <cfset variables.jackson = application.jackson />
    <cfset var json = jackson.writeValueAsString(variables.data) />

Just note that you'll need to JavaCast the variables from ColdFusion in order to get the correct boolean, numeric, and integer values (no auto-typing like the built in serializer.) Jackson is much faster and (despite the explicit typing required) more reliable than a custom serializer.

Upvotes: 1

Adam Cameron
Adam Cameron

Reputation: 29870

I'd say what you're seeing is a bug in ColdFusion 11, so you should raise it accordingly on the bug tracker.

Fortunately ColdFusion 11 has a (fairly poorly realised, IMO) mechanism for you to define your own serialisation process for components.

The docs for this functionality is at "Support for pluggable serializer and deserializer", and I go through some investigation on my blog here: "ColdFusion 11: custom serialisers. More questions than answers".

How to implement this is too long-winded for a Stack Overflow answer, and it's all well documented in the official docs.

Upvotes: 3

Related Questions