Last active
August 29, 2015 14:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[{"@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