Last active
November 26, 2021 20:07
-
-
Save bitsnaps/6ff2ad45dddf9962041de9be732f859b to your computer and use it in GitHub Desktop.
Groovy json (from/to) conversions simple examples
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
// Groovy from/to Json conversion | |
import groovy.json.* | |
// Object to Json | |
class Version { | |
int id | |
} | |
class User { | |
String className = this.class.simpleName.toLowerCase() | |
String name | |
int age | |
Version version | |
def toJson(){ | |
JsonOutput.toJson(this) | |
} | |
Object asType(Class clazz){ | |
if (clazz == JsonBuilder){ | |
new JsonBuilder(this)//.toPrettyString() | |
} | |
} | |
// works from both String & JsonBuilder | |
static /*groovy.json.internal.LazyMap*/ fromJson(def json){ | |
new JsonSlurper().parseText(json.toString()) | |
} | |
} | |
def user = new User(name:'Ali', age: 65, version: new Version(id:1)) | |
// Make use of JsonOutput | |
println(user.toJson()) | |
assert JsonOutput.toJson(user).class.simpleName == 'String' | |
// Make your own: "as Json" converter | |
def jsonUser = user as JsonBuilder | |
println(jsonUser) | |
assert jsonUser.class.simpleName == 'JsonBuilder' | |
assert user.toJson()==jsonUser.toString() | |
// JsonSlurper (parse a json text) | |
// LazyMap can be found at: "groovy.json.internal.LazyMap" or "org.apache.groovy.json.internal.LazyMap" in new versions of Groovy | |
assert new JsonSlurper().parseText(user.toJson()).getClass().simpleName.endsWith('LazyMap') | |
assert User.fromJson(jsonUser).className == 'user' | |
class Manager extends User{} | |
assert new User().className == 'user' | |
assert new Manager().className == 'manager' | |
//println((new Manager() as JsonBuilder).toPrettyString()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment