Skip to content

Instantly share code, notes, and snippets.

@kldavis4
Created January 24, 2013 21:06
Show Gist options
  • Select an option

  • Save kldavis4/4627743 to your computer and use it in GitHub Desktop.

Select an option

Save kldavis4/4627743 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class JacksonDeserializationTest {
@org.junit.Test
public void test() throws Exception {
Foo g1 = new Foo();
g1.setName("foo1");
List<Foo> foos = new ArrayList<Foo>();
foos.add(g1);
List<Bar> bars = new ArrayList<Bar>();
Bar bar1 = new Bar();
bar1.setFoos(foos);
bars.add(bar1);
Bar bar2 = new Bar();
bar2.setFoos(foos);
bars.add(bar2);
RootEntity rootEntity = new RootEntity();
rootEntity.setFoos(foos);
rootEntity.setBars(bars);
for ( Bar bar : rootEntity.getBars() ) {
bar.setRootEntity(rootEntity);
}
ObjectMapper mapper = new ObjectMapper();
RootEntity deserialized = mapper.readValue(mapper.writeValueAsString(rootEntity),RootEntity.class);
org.junit.Assert.assertEquals("Expected only one foo ", 1, deserialized.getFoos().size());
}
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public static class RootEntity
{
private List<Foo> foos;
private List<Bar> bars;
public List<Foo> getFoos() {
return foos;
}
public void setFoos(List<Foo> foos) {
this.foos = foos;
}
public List<Bar> getBars() {
return bars;
}
public void setBars(List<Bar> bars) {
this.bars = bars;
}
}
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public static class Foo
{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public static class Bar
{
private List<Foo> foos;
private RootEntity rootEntity;
public List<Foo> getFoos() {
return foos;
}
public void setFoos(List<Foo> foos) {
this.foos = foos;
}
public RootEntity getRootEntity() {
return rootEntity;
}
public void setRootEntity(RootEntity rootEntity) {
this.rootEntity = rootEntity;
}
public List<Foo> getRootEntityFoos() {
if (rootEntity != null ) {
return rootEntity.getFoos();
}
return new ArrayList<Foo>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment