Skip to content
Advertisement

Serialize Object/Object[] entries to gson JsonObject

I am reading a resource from a backend that is giving me an Map of entries. I am iterating these and retriving the values. The type of that value is object or object[], the actual types are common primitives or a Calender class.

My target is to create a json response, it should look like this:

JavaScript

But I am really unhappy with the result, since I am repeating a lot of checks and methods that are doing the same , the only thing that differs is are the types.

The first step I am doing is to check which class I am facing

JavaScript

After that I am creating the json entries with the help of a big if clause

JavaScript

getJsonArray is receiving the array types and creating JsonArray entries for example

JavaScript

Im sure theres a better way to achieve this 🙂

Advertisement

Answer

You can use toJsonTree method that recognizes automatically the object class.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement