Skip to content

Instantly share code, notes, and snippets.

@bfncs
Created December 11, 2020 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfncs/2626ff10830c29e674c6e485bcb7db67 to your computer and use it in GitHub Desktop.
Save bfncs/2626ff10830c29e674c6e485bcb7db67 to your computer and use it in GitHub Desktop.
Jackson: Deserializing to single-value Record from scalar values
package us.byteb.jackson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.Objects;
public class RecordStringDeserializationTest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Test
void deserializeMyValueRecordFromPrimitiveValue() throws Exception {
assertEquals(
new MyValueRecord("foo"),
OBJECT_MAPPER.readValue("\"foo\"", MyValueRecord.class));
}
@Test
void deserializeMyValueRecordFromObj() throws Exception {
assertEquals(
new MyValueRecord("foo"),
OBJECT_MAPPER.readValue("{\"value\":\"foo\"}", MyValueRecord.class));
}
@Test
void deserializeMyValueWithFactoryMethodFromPrimitiveValue() throws Exception {
assertEquals(
new MyValueRecordWithFactoryMethod("foo"),
OBJECT_MAPPER.readValue("\"foo\"", MyValueRecordWithFactoryMethod.class));
}
@Test
void deserializeMyValueClassFromPrimitiveValue() throws Exception {
assertEquals(
new MyValueClass("foo"),
OBJECT_MAPPER.readValue("\"foo\"", MyValueClass.class));
}
final record MyValueRecord(@JsonProperty String value) {
@JsonValue
public String value() {
return value;
}
}
final record MyValueRecordWithFactoryMethod(@JsonProperty String value) {
@JsonCreator
public static MyValueRecordWithFactoryMethod of(final String value) {
return new MyValueRecordWithFactoryMethod(value);
}
@JsonValue
public String value() {
return value;
}
}
static class MyValueClass {
final String value;
public MyValueClass(@JsonProperty final String value) {
this.value = value;
}
@JsonValue()
public String getValue() {
return value;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MyValueClass that = (MyValueClass) o;
return Objects.equals(value, that.value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment