Exploring the process of building a JavaScript function inside a JSON object using Gson

Can Gson generate JSON that includes a JavaScript function without a key nested within?

{
    autosave: {
        save( editor ) {
            return editor.saveData( editor.id, editor.getData() );
        },
        waitingTime: 2000
}

Appreciate any help. Thanks.

Answer №1

After much exploration, I have discovered a solution using TypeAdapterFactory. Below is the implementation:

class AutosaveAdapter implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> tokenType) {
        final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType);

        return new TypeAdapter<T>() {
            @Override
            public T read(JsonReader reader) throws IOException {
                return adapter.read(reader);
            }

            @Override
            public void write(JsonWriter writer, T value) throws IOException {
                JsonElement tree = adapter.toJsonTree(value);

                if (value instanceof Autosave) {
                    String dom = value.toString();
                    JsonObject jo = (JsonObject) tree;
                    jo.addProperty("autosave", dom );
                }
                gson.getAdapter(JsonElement.class).write(writer, tree);
            }
        };
    }
}

Furthermore,

class Autosave {

    int waitingTime;

    @Expose(serialize = false, deserialize = false)
    String name;

    @Expose(serialize = false, deserialize = false)
    String arguments;

    @Expose(serialize = false, deserialize = false)
    String body;

    Autosave(int waitingTime, String name, String arguments, String body) {
        this.waitingTime = waitingTime;
        this.name = name;
        this.arguments = arguments;
        this.body = body;
    }

    public String toString() {
        return "{ waitingTime:" + waitingTime + "," +
                  name +" ( "+arguments+" ) { " + body + " } "+
                "}";
    }
    
}

To perform a test:

public static void main(String... args) {
        Autosave autosave = new Autosave(2000, "save", "editor", "return editor.saveData( editor.id, editor.getData() );");
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setLenient();
        Gson gson = gsonBuilder
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapterFactory(new AutosaveAdapter())
                .create();
        System.out.println(gson.toJson(autosave));
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using maxDate in Material UI DatePicker Component to set a maximum date limit

I'm having a tough time getting the maxDate property to function properly on the Material UI DatePicker component. It should disable dates after the specified maxDate. In my situation, I needed to set the maxDate to +60 days from the current Date(), ...

Determining Cost Using Quantity and Option Changes in Angular 4

Task In the shopping cart, there is a list of items with options, quantities, and prices. The goal is to calculate the total price based on any changes in the quantity and option of an item. Investigation I included [(ngModel)] for 2-way data binding, ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select). In my view, the following code is present: <select name="rubros" id="rubros" class="select2 form-control" ng-model="vm.comercio.tags" ng-options="rubro.nombre for rub ...

Different ways to dynamically change tailwind colors during execution

Utilizing tailwind v3, it's feasible to customize existing colors by modifying the tailwind.config file. https://tailwindcss.com/docs/customizing-colors module.exports = { theme: { extend: { colors: { gray: { ...

Highchart tip: How to create a scrollable chart with only one series and update the x-axis variable through drilldown

Before I pose my question, here is a link to my jsfiddle demo: http://jsfiddle.net/woon123/9155d4z6/1/ $(document).ready(function () { $('#deal_venue_chart').highcharts({ chart: { type: 'column' ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

"The function within the Sails.js model is not properly returning a value when rendered

Within my Sails.js application, I am currently attempting to retrieve the total number of users that have been approved in my database and utilize this count variable within my view by employing the count() query. Below is the snippet of code present in my ...

Refreshing DataTables with specific parameters using ajax.reload()

In my Angular2 project, I am utilizing DataTables with the serverSide feature. After making changes, I am attempting to reload the table and pass these changes as parameters in a POST request via AJAX. The issue I am encountering is that DataTables alway ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...

I tried to use my Google Maps app, but for some reason, it failed

Here's the code snippet I've been working on: if($_POST){ // get latitude, longitude and formatted address $data_arr = geocode($_POST['address']); // if able to geocode the address if($data_arr){ $latitude = $data_arr[0]; $l ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

In the process of creating my initial discord bot, struggling to incorporate advanced functionalities beyond basic commands

I am currently using discord.js and JavaScript to code. I have created a test bot and followed step-by-step guides meticulously, but the bot only responds to basic "ping pong" commands. Whenever I try to add more complex commands, the bot stops functioning ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

Traversing through JSON objects in Angular 2

I am currently facing an issue while trying to iterate through a JSON object. Below is the sample JSON data: floors.ts this.floors= [ { floorName: "floor 1", result: [ { resFloor: "1", ...

I am attempting to update the background image pattern every time the page refreshes. Despite trying numerous codes, I have not been able to achieve the

Here is my code that I've been struggling with. I am trying to change the image on page refresh, but it's not working as expected. <SCRIPT LANGUAGE="JavaScript"> var theImages = new Array() theImages[0] = 'images/1.png' ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Retrieving the name of an object from an array using Javascript

const crypto = require("crypto-js"); const hashFunctions = [crypto.MD5, crypto.SHA1, crypto.SHA256, crypto.SHA224, crypto.SHA512, crypto.SHA384, crypto.SHA3, crypto.RIPEMD160]; console.log(JSON.stringify(hashFunctions[0])); The above code outputs undefin ...

Arranging ng-grid by a hidden column

Imagine having an array of objects structured like this: { name: ... age: ... dept: ... } Now, if you want to display these objects in an ng-grid with only columns for name and age, you can set it up like this: columnDefs: [{field:'name' ...