How to make Jackson databind communicate with Json.Net

31 Views Asked by At

So let's say I have bidirectional relations between two objects (getter and setters omitted):

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
            property="$id")
    public class Author {
        @JsonProperty("$id")
        private int id;
        private String name;
        private List<Book> books;
    }
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
            property="$id")
    public class Book {
        @JsonProperty("$id")
        private int id;
        private String title;
        private List<Author> authors;
    }

I can then create an object I want to serialize:

        Author tolkien = new Author();
        tolkien.id = 1;
        tolkien.name = "J.R.R. Tolkien";
        tolkien.books = Arrays.asList(new Book(), new Book());
        tolkien.books.get(0).id = 2;
        tolkien.books.get(0).title = "Lord of the Rings";
        tolkien.books.get(0).authors = List.of(tolkien);
        tolkien.books.get(1).id = 3;
        tolkien.books.get(1).title = "The Dragon Hunter";
        tolkien.books.get(1).authors = List.of(tolkien);

        System.out.println(objectMapper.writeValueAsString(tolkien));

this will print:

{
  "$id" : 1,
  "name" : "J.R.R. Tolkien",
  "books" : [ {
    "$id" : 2,
    "title" : "Lord of the Rings",
    "authors" : [ 1 ]
  }, {
    "$id" : 3,
    "title" : "The Dragon Hunter",
    "authors" : [ 1 ]
  } ]
}

This is 99% of the work, but the way JSON.NET is serializing the object references is closer to JSON Schema standard and makes use of a similar API, writing the reference as an object instead of just an id (which IMHO is much better because it allows to recognize references from data):

{
  "$id" : 1,
  "name" : "J.R.R. Tolkien",
  "books" : [ {
    "$id" : 2,
    "title" : "Lord of the Rings",
    "authors" : [ {"$ref": 1} ]
  }, {
    "$id" : 3,
    "title" : "The Dragon Hunter",
    "authors" : [ {"$ref": 1} ]
  } ]
}

How can I make the two services interoperable from Java/Jackson's side (I cannot modify the .NET code)?

0

There are 0 best solutions below