Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Created January 21, 2023 03:13
Show Gist options
  • Save alexanderankin/0d17c53fb3d4d8daf7356deb06d2f5d8 to your computer and use it in GitHub Desktop.
Save alexanderankin/0d17c53fb3d4d8daf7356deb06d2f5d8 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class JacksonSerializationExample {
@SneakyThrows
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
byte[] serialized = serialize(objectMapper.readTree("{\"a\": true, \"b\":[1,2,3]}"));
JsonNode deserialized = deserialize(serialized);
System.out.println(deserialized.get("b"));
}
@SneakyThrows
private static <T> T deserialize(byte[] serialized) {
try (ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(serialized))) {
@SuppressWarnings("unchecked")
T cast = (T) is.readObject();
return cast;
}
}
@SneakyThrows
private static byte[] serialize(JsonNode jsonNode) {
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(bytes)) {
stream.writeObject(jsonNode);
return bytes.toByteArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment