Created
April 24, 2017 11:21
-
-
Save mjhagen/a332ad705c15e10d75d6e53213d2fca2 to your computer and use it in GitHub Desktop.
gson wrapper for CFML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
component accessors=true { | |
public component function init( root ) { | |
var jl = new javaloader.javaloader( [ root & "/lib/java/gson-2.7.jar" ] ); | |
variables.gson = jl.create( "com.google.gson.GsonBuilder" ) | |
.serializeNulls( ) | |
.create( ); | |
variables.structClass = createObject( "java", "java.util.LinkedHashMap" ).init( ).getClass( ); | |
var array = [ ]; | |
variables.arrayClass = array.getClass( ); | |
return this; | |
} | |
public string function serialize( required any source ) { | |
return variables.gson.toJsonTree( source ).toString( ); | |
} | |
public any function deserialize( required string source ) { | |
source = lTrim( source ); | |
var firstChar = left( source, 1 ); | |
switch ( firstChar ) { | |
case '{' : return deserializeStruct( source ); | |
case '[' : return deserializeArray( source ); | |
} | |
return; | |
} | |
public struct function deserializeStruct( required string source ) { | |
return duplicate( variables.gson.fromJson( source, variables.structClass ) ); | |
} | |
public array function deserializeArray( required string source ) { | |
return duplicate( variables.gson.fromJson( source, variables.arrayClass ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment