Spring JSON serialization, Gson deserialization

I currently have a problem with deserializing certain internal objects, in spring, I initialize all my objects before displaying them with @ResponseBody.

As an example, this is the answer:

[{id:1, location:{id:1, ... extra location data}},
 {id:2, location:1}
]

GSON now displays an error message because it cannot understand what location:1relates to a location object already deserialized in the previous object. Desamerization is performed as follows:

@Override
public void handleReader(Reader reader) {
    try {
        String json = readerToString(reader);
        T object = getGson().fromJson(json, returnType);
        handleObject(object);
    } catch (Exception e) {
        Sentry.captureException(e);
    }
}

As an example, this is called through a regular general class, I would use a type Event[]like T to return an array.

Gson make spring ? Gson, , .

spring :

@Override
public List<T> list() {
    return service.findAll();
}

:

@Override
@Transactional
public List<Event> findAll() {
    List<Event> list = eventRepository.findByArchivedFalse();
    for (Event event : list) {
        this.initialize(event);
    }
    return list;
}
@Override
public Event initialize(Event obj) {
    Hibernate.initialize(obj.getLocation());
    Hibernate.initialize(obj.getLocation().get... inner data here);
    return obj;
}

, , , , .

+4
1

, JSon. JSon - , .

1: JSon

, , , .

{
  "uniqueLocations":
    [
      {"id":1, ... extra location details} ,
    ],
  "locationMap":
    [ 
      {"id":1,"location":1},
      {"id":2,"location":1}
      ... etc.
    ]
}

; json , .


2: Gson

, , . , TypeAdapter, , , , , TypeAdapterFactory.

, , : TypeAdapterFactory Gson?

+2

All Articles