Mayank Soni
Mayank Soni

Reputation: 13

Get XML or JSON Representation from POGO

Is there way in groovy by which i can get either XML or JSON representation of that POGO, similar to what i can have in JAVA by annotating POJO?

Example:

Below POGO needs to converted to either JSON or XML at runtime

class User {
   String name
   String address
} 

I tried JSONBuilder, but could not find anything which can convert this to XML as well.

Upvotes: 1

Views: 432

Answers (1)

jalopaba
jalopaba

Reputation: 8129

As @cfrick comments, it is quite likely that your java library and annotations will work also for POGOs (are you using JAXB?).

Anyway, for JSON output, you can use JSONBuilder

class User {
   String name
   String address
}

def user = new User(name: 'John', address: 'Bake St.')
println new JsonBuilder(user).toPrettyString()
---
{
    "address": "Bake St.",
    "name": "John"
}

For a quick solution regarding XML, you can use XStream:

@Grapes(
    @Grab(group='com.thoughtworks.xstream', module='xstream', version='1.4.7')
)

import com.thoughtworks.xstream.*

[...]    

def xstream = new XStream()
println xstream.toXML(user)
---
<User>
  <name>John</name>
  <address>Bake St.</address>
</User>

If you want a kind of a "common" processing for JSON and XML, you can use groovy's builder mechanism, passing a closure with nested method calls and nested closures to the builder:

def userC = { 
    name('Kevin')
    address('Train St.')
}

def json = new JsonBuilder()
json userC
println json.toPrettyString()

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.'User' userC
println writer.toString()
---
{
    "name": "Kevin",
    "address": "Train St."
}
<User>
  <name>Kevin</name>
  <address>Train St.</address>
</User>

Or with the StaxBuilder, a builder that works with Stax processors. Using jettison, you can somehow unify JSON and XML processing:

@Grapes(
    @Grab(group='org.codehaus.jettison', module='jettison', version='1.3.7')
)

import javax.xml.stream.XMLOutputFactory
import javax.xml.stream.XMLStreamException

import groovy.json.*
import groovy.xml.*

import org.codehaus.jettison.mapped.*

def userC = { 
    name('Kevin')
    address('Train St.')
}

[...]

def factory = XMLOutputFactory.newInstance()
writer = new StringWriter()
def stax = new StaxBuilder(factory.createXMLStreamWriter(writer))
stax.'User' userC
println writer.toString()

def conv = new MappedNamespaceConvention()
writer = new StringWriter()
def mappedWriter = new MappedXMLStreamWriter(conv, writer)
staxJson = new StaxBuilder(mappedWriter)
staxJson.'User' userC
println writer.toString()
---
<?xml version="1.0" ?><User><name>Kevin</name><address>Train St.</address></User>
{"User":{"name":"Kevin","address":"Train St."}}

Upvotes: 1

Related Questions