Skip to content

Instantly share code, notes, and snippets.

@silmeth
Created January 23, 2018 14:20
Show Gist options
  • Save silmeth/ed06498d44770471bbd355f2df8f4d57 to your computer and use it in GitHub Desktop.
Save silmeth/ed06498d44770471bbd355f2df8f4d57 to your computer and use it in GitHub Desktop.
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class TypeReferenceTest {
@Test
public void test() throws Exception {
final String str = "[{\"foo\": 3, \"bar\": \"boo\" }, { \"foo\": -3, \"bar\": \"boo2\" }]";
List<Object> value = new ObjectMapper().readValue(str, new TypeReference<List<Foo>>() { });
System.out.println(value); // prints [Foo(foo = 3, bar = "boo"), Foo(foo = -3, bar = "boo2")]
assertEquals(asList(new Foo(3, "boo"), new Foo(-3, "boo2")), value);
}
static class Foo {
@JsonCreator
Foo(@JsonProperty("foo") int foo, @JsonProperty("bar") String bar) {
this.foo = foo;
this.bar = bar;
}
@JsonProperty("foo")
int foo;
@JsonProperty("bar")
String bar;
@Override
public String toString() {
return "Foo(foo = " + foo + ", bar = \"" + bar + "\")";
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Foo)) {
return false;
}
Foo that = (Foo) other;
return this.foo == that.foo && this.bar.equals(that.bar);
}
@Override
public int hashCode() {
throw new IllegalStateException("unimplemented");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment