Marcos de las Heras Marcos de las Heras - 24 days ago 12
Java Question

Convert List<Item> to json

I am having a List like following,

List<Item> EquipmentData = SAPEquipment.getByFilter(filter);


That item is the result I'm getting from SAP ("com.vaadin.data.util.sqlcontainer.RowItem")

My problem is that i need to convert that List to Json format. I've been reading some examples and tried using Gson like that:

Gson gson = new Gson();
gson.toJson(EquipmentData);


also tried with just one item

gson.toJson(EquipmentData.get(0));


The error reported is the following one:

java.lang.StackOverflowError
com.google.gson.stream.JsonWriter.string(JsonWriter.java:559)
com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:402)
com.google.gson.stream.JsonWriter.beginObject(JsonWriter.java:307)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:214)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:208)
com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:145)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:99)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:219)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:99)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:219)
com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:899)


I cannot modify that List so I will need a proper way to convert it.

Any tip will be highly appreciated

EDIT : Added Item Class link (vaadin.com/api/com/vaadin/data/Item.html)

EDIT2: Added full stacktrace /

Answer

The reason for Stackoverflow might be because of the recursive mappings in your Item class. One way to fix this is to iterate through the EquipmentData list and set your return object(DTO) then convert the DTO using GSON.