How to save a list of POJOs in my JsonDocument?

Hi

I am trying to save a list of points in a structure like this:

    {
        "id": 797,
        "name": "Rudbøl Sø",
        "points": [
            {
                "lon": "8.7889129103",
                "lat": "54.9007764066"
            },
            {
                "lon": "8.8068412967",
                "lat": "54.9086568131"
            },
            {
                "lon": "8.7912673708",
                "lat": "54.9041377725"
            },
            {
                "lon": "8.7601299969",
                "lat": "54.8950937050"
            }
        ]
    },

In my java code the list of points are List<Point> ie. a simple Java list.

I have tried to save it like this (simplified):

protected boolean updateField(JsonObject node, final String field, final List<?> value) {
   JsonArray vNew = JsonArray.from(value);
   node.put(field, vNew);
   return true;
}

But that appears to not be possible. It seems that my code hangs around the node.put(...). Do I have to manually create a new JsonArray, create an JsonObject for each POJO, and use ...put() as String/Double for each of the attributes??

Hi @jda. JsonArray.from should throw an IllegalArgumentException as it supports only a subset of types (Strings, Integers, BigDecimal, JsonObject & JsonArray, and similar). It won’t automatically serialize your Point class.

Personally I would do as you suggest, build it up with JsonObjects. But you could also consider using a JSON library like Jackson to serialise your object graph into a string, and then use our RawJsonDocument to store it. Or, if your object graph is Serializable, you could use SerializableDocument, which is the closest in convenience to what you’re looking for. Please see the JsonDocument docs for more on those options.

2 Likes

Thanks @graham.pople!

It doesn’t throw an exception but just seems to hang/stop… - anyway, I had figured out that I was probably doing it wrong.

I have made a small method to create the JsonArray by adding one JsonObject with the primitive datatypes for each object :wink:

Hi @jda. I’m glad you’ve found a way forward. I did try quickly to replicate the hang problem but was unable to, it throws the exception as expected for me. Not quite sure what’s going on there.