Last active
January 15, 2016 21:56
-
-
Save RaviH/58835200a886cd8d7b9a to your computer and use it in GitHub Desktop.
Gist to convert Json string to a specific object type
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 com.charter.aesd.activationlogin.edge.rest | |
import groovy.json.JsonBuilder | |
import groovy.json.JsonSlurper | |
import groovy.transform.ToString | |
/** | |
* Created by rhasija on 1/15/16. | |
*/ | |
class JsonToObject { | |
public static void main(String[] args) { | |
// Person object | |
def person = new Person(firstName: "John", lastName: "Doe") | |
// Json String | |
def personJSON = new JsonBuilder(person).toPrettyString() | |
// Json String to Map | |
def personMap = new JsonSlurper().parseText(personJSON) | |
// using Map to convert to Person object type | |
def newPerson = new Person(personMap) | |
println(person) | |
println(newPerson) | |
assert newPerson.firstName == person.firstName | |
assert newPerson.lastName == person.lastName | |
} | |
} | |
@ToString | |
class Person { | |
String firstName | |
String lastName | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment