Search code examples
gson

Add function to GSON JsonObject


My target is to generate the JSON configuration of an apexchart ( https://apexcharts.com/javascript-chart-demos/bar-charts/custom-datalabels/ ) in Java with GSON.

The configuration contains a property "formatter" that has a JavaScript function as a value:

formatter: function (val, opt) {
  return opt.w.globals.labels[opt.dataPointIndex] + ":  " + val
  },

When I add a property to a JsonObject like this jsonDataLabels.addProperty("formatter", "(val, opt) {...}"); then the property value in the output is (as expected) a String (with quotes) and apexchart doesn't interpret it.

How can I add an unquoted JavaScript function into a GSON JsonObject?


Solution

  • How can I add an unquoted JavaScript function into a GSON JsonObject?

    The short answer is you can't; Gson is a JSON library and what you are creating is not JSON but a JavaScript object.

    However, you might be able to achieve this with Gson's JsonWriter.jsonValue method. That method is intended to write a raw JSON value, but you could misuse it to write your JavaScript function value:

    JsonWriter jsonWriter = new JsonWriter(...);
    jsonWriter.beginObject();
    jsonWriter.name("formatter");
    jsonWriter.jsonValue("function (val, opt) { ... }");
    jsonWriter.endObject();
    

    But be careful because jsonValue does not check the syntax of the provided value, so if you provide a malformed value, the resulting JSON (or in your case JavaScript object) might be malformed.

    Maybe there are JavaScript code writer libraries out there though, which would be better suited for your use case.