Skip to content

Instantly share code, notes, and snippets.

@aruizca
Created July 28, 2015 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruizca/8ceaaabfbea8ad8f03bf to your computer and use it in GitHub Desktop.
Save aruizca/8ceaaabfbea8ad8f03bf to your computer and use it in GitHub Desktop.
This shows the problems with the use of the JSONObject.NULL class by the Grails JSON converter
package grails.converters.tests
import grails.converters.JSON
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
import spock.lang.Specification
/**
* Created by Angel Ruiz.
*/
class JSONObjectNullSpec extends Specification {
def "problems examples with JSONObject.NULL"() {
given:
def jsonPayload = JSON.parse("{'myValue': null}")
when: "this shows that if we expect a String but for whatever reason our json payload contains null"
String myValue = jsonPayload.myValue
then: "myValue will be \"null\""
myValue == "null"
when:
myValue = jsonPayload.myValue
def isValueSaved = false
if (myValue) {
// save to DB
isValueSaved = true
}
then: "the validation does not work because I have casted it to String which is what I normally expect"
isValueSaved == true // This means the String "null" has been saved to the DB
}
def "other problems with JSONObject.NULL casting"() {
// Important! This particular use case cannot be fixed with my workaround because the ideal solution would be for the JSONObject.NULL disappear an get replaced by null
when: "this shows that if you are expecting an array list but for whatever reason our json payload is null you get an exception"
def object = JSON.parse("{'myList':null}")
List myList = object.myList
then: "Fails because JSONObject.Null cannot be implicitly casted to anything but Object."
thrown(GroovyCastException)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment