Skip to content

Instantly share code, notes, and snippets.

@cowwoc
Created November 28, 2014 19:10
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 cowwoc/743d2839bc7297a47516 to your computer and use it in GitHub Desktop.
Save cowwoc/743d2839bc7297a47516 to your computer and use it in GitHub Desktop.
package com.mycompany.jackson639;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
public class Main {
public static final class Context {
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public static final class Parent1 {
@JsonProperty
public Optional<Child1> child;
@JsonCreator
public Parent1() {
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public static final class Parent2 {
private final Context context;
@JsonProperty
public Optional<Child2> child;
@JsonCreator
public Parent2(@JacksonInject Context context) {
this.context = context;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public static final class Child1 {
@JsonProperty
private final Parent1 parent;
@JsonCreator
public Child1(@JsonProperty("parent") Parent1 parent) {
this.parent = parent;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public static final class Child2 {
private final Context context;
@JsonProperty
private final Parent2 parent;
@JsonCreator
public Child2(@JacksonInject Context context,
@JsonProperty("parent") Parent2 parent) {
this.context = context;
this.parent = parent;
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Context context = new Context();
InjectableValues iv = new InjectableValues.Std().
addValue(Context.class, context);
mapper.setInjectableValues(iv);
Parent1 parent1 = new Parent1();
Child1 child1 = new Child1(parent1);
parent1.child = Optional.of(child1);
Parent2 parent2 = new Parent2(context);
Child2 child2 = new Child2(context, parent2);
parent2.child = Optional.of(child2);
File file = new File("target/test1.xml");
mapper.writeValue(file, parent1);
parent1 = mapper.readValue(file, Parent1.class);
System.out.println("This works: " + parent1);
file = new File("target/test2.xml");
mapper.writeValue(file, parent1);
parent2 = mapper.readValue(file, Parent2.class);
System.out.println("This fails: " + parent2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment