Skip to content

Instantly share code, notes, and snippets.

@itzg
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itzg/34beade3a355b0034a11 to your computer and use it in GitHub Desktop.
Save itzg/34beade3a355b0034a11 to your computer and use it in GitHub Desktop.
How to write out a collection/list of objects with Fastxml Jackson JSON and retain the JsonTypeInfo. Solution was derived from http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp
@Grapes(
@Grab(group='com.fasterxml.jackson.core', module='jackson-databind', version='2.2.4')
)
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.CollectionType
import com.fasterxml.jackson.databind.type.TypeFactory
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="@class")
class MyObject {
String name
int age
}
ObjectMapper objectMapper = new ObjectMapper();
CollectionType listOfMine = TypeFactory.defaultInstance()
.constructCollectionType(List, MyObject);
def listOfObjects = [new MyObject(name: "One", age: 1),
new MyObject(name: "Two", age: 2),
new MyObject(name: "Three", age: 3)]
def objectWriter = objectMapper.writerWithType(listOfMine)
println objectWriter.writeValueAsString(listOfObjects)
[{"@class":"MyObject","name":"One","age":1},{"@class":"MyObject","name":"Two","age":2},{"@class":"MyObject","name":"Three","age":3}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment