Skip to content

Instantly share code, notes, and snippets.

@RaviH
Last active January 15, 2016 21:56
Show Gist options
  • Save RaviH/58835200a886cd8d7b9a to your computer and use it in GitHub Desktop.
Save RaviH/58835200a886cd8d7b9a to your computer and use it in GitHub Desktop.
Gist to convert Json string to a specific object type
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