Created
July 28, 2015 00:35
-
-
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
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
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