gsonvert.xvertx-eventbus

How can I serialize and deserialize vert.x JsonObject and JsonArray using google gson


I am using vertx i need to transfer data using eventbus from one verticle to another so in order to fast that process need to serialize and deserialize data to save memory as vertx keeps messages in queue and also performance and time as converting JsonObject to String is slower than converting using gson. Below is my sample code:


package com.test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

public class Test44
{
    private static Gson gson = new GsonBuilder()
            .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
            .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
            .create();

    public static void main(String[] args) throws Exception {

        var js = new JsonObject();

        js.put("test","dddd").put("aaa","dddd").put("res",new JsonObject().put("interface",new JsonArray().add("aaaa")));

        var s = gson.toJson(js);

        var d = gson.fromJson(s,JsonObject.class);

        System.out.println(d);
    }
}

In this i get following output from above code

{"test":"dddd","aaa":"dddd","res":{"map":{"interface":{"list":["aaaa"]}}}} but i need following when i decode json back from gson string

{"test":"dddd","aaa":"dddd","res":{"interface":{["aaaa"]}}

Any idea how it can be done

i am using following lib vertx-core 4.4.0 and gson 2.10.1


Solution

  • Gson does not know any of the Vert.x classes such as io.vertx.core.json.JsonArray, so it uses reflection and accesses their internal fields. This is why you see the additional properties map and list in the JSON data.

    Either use only Gson classes or only Vert.x classes, but don't mix them. Gson has the corresponding classes com.google.gson.JsonObject and com.google.gson.JsonArray.

    However, Vert.x seems to use Jackson by default, so it would surprise me a bit that its performance is worse than the performance of Gson.

    Maybe it would be good if you asked in a separate Stack Overflow question why you are seeing bad performance with the Vert.x classes, and providing the code you used for measuring performance.