Groovy + JSON, in an OSGi container?

Friday, October 22, 2010

Very specific usage, yes, but I needed it for a custom script in a Day CQ5 project. The popular JSON-lib library has integrated Groovy support, but devolves into dependency hell when attempting to load into an OSGi container. Rather than plunge myself into a minor nightmare, I instead opted for the Jackson JSON Processor, which contains the necessary bundle metadata, but no built-in Groovy support. HOWEVER, their ObjectMapper class can bind a JSON string to a Map, which allows me to harness the beauty of Groovy map navigation. Behold.

import org.codehaus.jackson.map.ObjectMapper
def json = new ObjectMapper().readValue('{"type":"beer","quantity":"2","properties":[{"name":"IBU","value":"99"}]}', Map.class)
assert json.type == 'beer'
assert !json.properties.isEmpty()
assert json.properties[0].name == 'IBU'
Top