Skip to content
Advertisement

How to serialize objects to json?

I have a list of objects which I want to serialize to json. I am using the following code to do this:

    private ByteBufferOutputStream serializeEvents(List<Event> events){

        final ByteBufferOutputStream outputStream = new ByteBufferOutputStream(1024, true, false);
        try{
            for (Event event : events) {
                Json.writeValueAsToOutputStream(event, outputStream);
                outputStream.write('n');
            }
            return outputStream;
        }
        catch (Exception e){
            log.error("Error serializing data", e);
            return null;
        }
    }

it works as expected but in this case if there is an exception the whole list of events would be discarded. What I want is to skip any individual event if it fails to serialize. Plus these are json lines delimitted by ‘n’ as I am uploading the stream to s3 and want to be queryable by athena.

   final ByteBufferOutputStream serializedEvent = serializeEvents(events);

   if (serializedEvent != null) {
            try {
                s3Client.putObject(objectRequest, RequestBody.fromByteBuffer(serializedEvent.toByteBuffer()));
                return true;
            } catch (S3Exception e) {
                log.error("Failed to send raw data events to S3", e);
                return false;
            }
        }

Advertisement

Answer

To easily serialize objects to json in Java, I suggest using the GSON library.

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

You can then turn this back to a Java object with

List<Event> events = gson.fromJson(string, Event.class);
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement