Last active
October 17, 2016 20:33
-
-
Save crazy4groovy/5031ace02894eaed7ab9 to your computer and use it in GitHub Desktop.
Create an Immutable Class instance from JSON? Let's see!
This file contains hidden or 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
import groovy.json.* | |
import groovy.transform.Immutable | |
enum Fruit { | |
Orange, | |
Apple | |
} | |
enum Car { | |
Ford('slow'), | |
Porsche('fast') | |
private String speed | |
Car(String speed) { | |
this.speed = speed | |
} | |
@Override | |
String toString() { | |
return speed | |
} | |
} | |
@Immutable(copyWith = true) | |
class Person { | |
String name | |
String[] phones = ['123'] as String[] | |
String now = new Date() | |
Fruit fruit = Fruit.Apple | |
Car car = Car.Ford | |
} | |
@Immutable(copyWith = true) | |
class Foo { | |
String bar | |
} | |
Person p = new Person(name: 'Steve') | |
String json = new JsonBuilder(p) | |
println json.class | |
println json // eg. {"phones":["123"],"now":"Thu Mar 10 10:40:16 EST 2016","car":"Ford","fruit":"Apple","name":"Steve"} | |
Map map = new JsonSlurper().parseText(json) as HashMap | |
/*Foo error = new Foo(map) //error! | |
assert error.bar == null*/ | |
Person target = new Person(map) | |
assert target.name == 'Steve' | |
assert target.phones == (['123'] as String[]) | |
println target.now // eg. 'Thu Mar 10 10:40:16 EST 2016' | |
assert target.fruit == Fruit.Apple | |
assert target.fruit.toString() == 'Apple' | |
assert target.car == Car.Ford | |
assert target.car.toString() == 'slow' | |
println 'Fin' |
This file contains hidden or 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.transform.Immutable(knownImmutableClasses = [Address]) | |
class Person { | |
Address address | |
} | |
@groovy.transform.Immutable | |
class Address { | |
String city | |
} | |
Person p = new Person([address: [city: 'Toronto']]) | |
assert p.address.city == 'Toronto' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment