Skip to content

Instantly share code, notes, and snippets.

@wsargent
Created November 27, 2020 02:07
Show Gist options
  • Save wsargent/5af0efdfc5427a15fdc3a7a5dd3f35bc to your computer and use it in GitHub Desktop.
Save wsargent/5af0efdfc5427a15fdc3a7a5dd3f35bc to your computer and use it in GitHub Desktop.
package com.tersesystems.buffer.serde;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.smile.SmileParser;
import java.io.ByteArrayOutputStream;
import java.util.function.Function;
import static com.fasterxml.jackson.dataformat.smile.SmileGenerator.Feature.CHECK_SHARED_NAMES;
import static com.fasterxml.jackson.dataformat.smile.SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES;
/**
* This is used for converting SMILE back to JSON in the dump format.
*/
public class SmileToJson implements Function<byte[], byte[]> {
private static SmileFactory smileFactory = new SmileFactory();
private static final JsonFactory jsonFactory = new JsonFactory();
static {
smileFactory = smileFactory.disable(CHECK_SHARED_NAMES).disable(CHECK_SHARED_STRING_VALUES);
}
private SmileToJson() {
}
public static SmileToJson instance() {
return SingletonHolder.instance;
}
private final static class SingletonHolder {
private final static SmileToJson instance = new SmileToJson();
}
public byte[] apply(byte[] bytes) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (
SmileParser sp = smileFactory.createParser(bytes);
JsonGenerator jg = jsonFactory.createGenerator(bos)
) {
while (sp.nextToken() != null) {
jg.copyCurrentEvent(sp);
}
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment