Created
January 21, 2023 03:13
-
-
Save alexanderankin/0d17c53fb3d4d8daf7356deb06d2f5d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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