Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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