Thursday, May 16, 2013

POJO to JSON : binding and serializing

//see: http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
//see: https://github.com/FasterXML/jackson-databind

@Grapes([
/*
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-core', version='2.2.1'
  ),
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-annotations', version='2.2.1'
  ),
*/
  @Grab(
    group='com.fasterxml.jackson.core', module='jackson-databind', version='2.2.1'
  )
])
import com.fasterxml.jackson.databind.ObjectMapper

class Abc {
    int id, age
    String person
}

ObjectMapper mapper = new ObjectMapper();
Abc entry = mapper.readValue('{"id": 1, "person": "Steve", "age": "1"}', Abc.class);

assert entry1.id == 1
assert entry1.person == "Steve"
assert entry1.age == 1 //notice the auto type conversion from the JSON!

def entry2 = mapper.readValue('{"id": 1, "person": "Steve", "age": [1, {}, 3]}', LinkedHashMap.class);

assert entry2.id == 1
assert entry2.person == "Steve"
assert entry2.age.size() == 3
assert entry2.age[1].getClass().name == 'java.util.LinkedHashMap'


mapper.writeValue(new File("C:\\result.json"), entry1)  //--> {"id":1,"person":"Steve","age":1}
/*
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.File, java.lang.Object)
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.OutputStream, java.lang.Object)
  public void com.fasterxml.jackson.databind.ObjectMapper#writeValue(java.io.Writer, java.lang.Object)
*/

No comments:

Post a Comment