Groovy web console

subscribe to the feed Subscribe
to this
site

JsonSlurper: extra/missing fields

Published 2 months ago by william
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class Foo {
  int x
  String toString() { "Foo(x=${x})" }
}

class Bar {
  int x
  int y
  String toString() { "Bar(x=${x},y=${y})" }
}

def parseThing(thing, Class responseClass) {
  return new groovy.json.JsonSlurper().parseText(thing).asType(responseClass)
}

Class fooClass = Foo
Class barClass = Bar
def str = '{"x":123, "y":456}'
println(parseThing(str, fooClass))
println(parseThing(str, barClass))
println()

str = '{"a":123, "y":456}'
println(parseThing(str, fooClass))
println(parseThing(str, barClass))