Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Unmarshalling JSON to a Specific Object

DZone's Guide to

Groovy Unmarshalling JSON to a Specific Object

A code snippet to use Groovy's default map-based constructor to convert JSON strings to an object type.

· Big Data Zone
Free Resource

Need to build an application around your data? Learn more about dataflow programming for rapid development and greater creativity. 

If you have a simple POJO (Plain Old Java Object) or POGO (Plain Old Groovy Object), you can use Groovy's default Map-based constructor to convert the JSON string to an Object type.

package com.example.groovy

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.equals(person.firstName)
        assert newPerson.lastName.equals(person.lastName)
    }
}

@ToString
class Person {  
    String firstName
    String lastName
}

Please let me know if you found this helpful. Thanks!

Check out the Exaptive data application Studio. Technology agnostic. No glue code. Use what you know and rely on the community for what you don't. Try the community version.

Topics:
big data ,json ,string ,java ,groovy

Published at DZone with permission of Ravi Hasija, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}