Panteleev Dima
Panteleev Dima

Reputation: 185

Is there a way to use Marshaller in Grails to parse JSON string into a custom object

I am trying to parse a JSON String to my custom object I already have a Marshaller class to go from the object to JSON and was wondering if it possible to use it for parsing in other direction as well instead of using JsonSlurper didn't see any clear documentation on that or any other JSON to object mapping api that is not includes writing code using JsonSlurper to manually create objects

Upvotes: 0

Views: 142

Answers (1)

daggett
daggett

Reputation: 28564

groovy supports simple mapping like this:

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

class A{
    int id
    String name
}

Map m = new JsonSlurper().parseText('{"id":123,"name":"Joe"}')
A a = m as A
assert a.id==123
assert a.name=="Joe"

def json = JsonOutput.toJson(a)
assert json == '{"id":123,"name":"Joe"}'

for marshalling/unmarshalling approach I prefer to use Gson library:

@Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson

class A{
    int id
    String name 
}

A a=new Gson().fromJson('{"id":123,"name":"Joe"}', A.class)
assert a.id==123
assert a.name=="Joe"

def json = new Gson().toJson(a)
assert json == '{"id":123,"name":"Joe"}'

Upvotes: 1

Related Questions