Question

In Java, if I want to transform some JSON into a POJO (or vice veersa), I'll use Gson or even FlexJson to do the conversion for me inside some kind of mapper object:

public interface JsonMapper<T> {
    public T toPojo(String json);
    public String toJson(T pojo);
}

public class WidgetJsonMapper implements JsonMappper<Widget> {
    private Gson mapper;

    @Override
    public Widget toPojo(String json) {
        // Use mapper to deserialize JSON into POJO
    }

    @Override
    public String toJson(Widget pojo) {
        // Use mapper to serialize a Widget instance into a JSON string.
    }
}

etc. I'm wondering how the game changes here when we're talking about Groovy. I see Grooovy has a JsonSlurper built right into it and was wondering if that could be used in lieu of a JSON mapping framework (like Gson) somehow.

Was it helpful?

Solution

Gson can also be used in Groovy for parsing JSON to POGO and vice-versa. Same goes with JsonSlurper and JsonBuilder respectively. An example using both ways:

@Grab( 'com.google.code.gson:gson:2.8.0' )
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

class Book {
    String name
    int isbn
    List<Author> authors
}

class Author {
    String name
    int age
}

def jsonString = '''
{
    "name": "Groovy", 
    "isbn": 12345, 
    "authors": [{
        "name": "John Doe", 
        "age": 30
     }, {
        "name": "Bill Nash", 
        "age": 40
     }] 
}
'''

//To Test
void assertions( book ) {
  book.with {
    assert name == 'Groovy'
    assert isbn == 12345
    assert authors
    assert authors[0].name == 'John Doe'
    assert authors[0].age == 30
    assert authors[1].name == 'Bill Nash'
    assert authors[1].age == 40
  }
}

/* JSON To POGO*/
//Using JsonSlurper
def book = new Book( new JsonSlurper().parseText( jsonString ) )
assertions book

//Using GSON
Gson gson = new Gson()
def bookUsingGson = gson.fromJson( jsonString, Book )
assertions bookUsingGson 

/* POGO To JSON */
//Using JsonBuilder
println new JsonBuilder( book ).toPrettyString()

//Using Gson
println gson.toJson( bookUsingGson )

//Using GsonBuilder for customization
GsonBuilder builder = new GsonBuilder()

// enable pretty print and seriliaze nulls
builder.setPrettyPrinting().serializeNulls()

// customize field title
builder.fieldNamingStrategy = { field -> field.name == "name" ? "title" : field.name }

// use the GsonBuilder to create a gson
Gson gsonBuilder = builder.create()

// pretty print
println gsonBuilder.toJson( bookUsingGson )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top