Skip to content

Instantly share code, notes, and snippets.

@s1ac2x1
Created November 7, 2017 15:44
Show Gist options
  • Save s1ac2x1/3026801f0b604dc77269da01bb44cd97 to your computer and use it in GitHub Desktop.
Save s1ac2x1/3026801f0b604dc77269da01bb44cd97 to your computer and use it in GitHub Desktop.
JSON bidirectional relationships
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class Test {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
private static class Order {
public long id;
public double marketPrice = Double.NaN;
public Execution execution;
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
private static class Execution {
public long id;
public double amount = Double.NaN;
public Order order;
}
public static void main(String[] args) throws IOException {
Order order = new Order();
order.marketPrice = 75.12;
Execution execution = new Execution();
execution.amount = 2;
order.execution = execution;
execution.order = order;
String serialized = new ObjectMapper().writeValueAsString(order);
System.out.println(serialized);
}
}
/**
* The result is:
* {
* "id":0,
* "marketPrice":75.12,
* "execution": {
* "id":0,
* "amount":2.0,
* "order":0
* }
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment