How can a deserialize a JSON representing a variant, using the Java bindings?

I’m using the variant example from this section of the Daml docs: Generate Java Code from Daml — Daml SDK 2.6.1 documentation

The Daml code for the variant and a piece of sample data is as follows:

data BookAttribute = Pages Int
                   | Authors [Text]
                   | Title Text
                   | Published with year: Int; publisher: Text
    deriving(Eq, Show)

pages : BookAttribute
pages = Pages 100

The JSON representation of pages generated by Daml Repl is as follows:

{"tag":"Pages","value":100}

When I try to deserialize this JSON with Gson in the following way:

import com.daml.quickstart.model.bookattribute.bookattribute.Pages;
import com.google.gson.Gson;

public class ParsingMain {

  public static void main(String[] args) {
    Gson g = new Gson();
    String pagesJson = "{\"tag\":\"Pages\",\"value\":100}";
    Pages pages = g.fromJson(pagesJson, Pages.class);
    System.out.println(pages);
  }
}

I get printed out Pages(null) which means I’m doing something wrong.

What is it?

The standard Gson decoding isn’t going to be able to decode the format used by the JSON API.

There is nothing in the Java bindings at the moment to decode that format so you’ll have to write your own decoder or build on the library used by the HTTP JSON API. Keep in mind that this library is written for internal use though so docs are lacking and it’s not officially supported.

Thank you, Moritz!