Reputation: 1447
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;
}
}
Upvotes: 0
Views: 2090
Reputation: 747
Serializing objects to Json in Java and back can be done as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
...
Event event; // event should be instantiated (must not be null)
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(event);
Event event2 = objectMapper.readValue(json, Event.class); // event and event2 are equal
Upvotes: 0
Reputation: 200
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>
Upvotes: 1