下面列出了com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair#com.fasterxml.jackson.databind.json.JsonMapper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
default void handleHashrateSubmit(
final JsonMapper mapper,
final MiningCoordinator miningCoordinator,
final StratumConnection conn,
final JsonRpcRequest message)
throws IOException {
final String hashRate = message.getRequiredParameter(0, String.class);
final String id = message.getRequiredParameter(1, String.class);
String response =
mapper.writeValueAsString(
new JsonRpcSuccessResponse(
message.getId(),
miningCoordinator.submitHashRate(
id, Bytes.fromHexString(hashRate).toBigInteger().longValue())));
conn.send(response + "\n");
}
public void testSnakeCaseNamingStrategy() throws Exception
{
String json = "{\"lower_endpoint\": 12, \"lower_bound_type\": \"CLOSED\", \"upper_endpoint\": 33, \"upper_bound_type\": \"CLOSED\"}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(12), r.lowerEndpoint());
assertEquals(Integer.valueOf(33), r.upperEndpoint());
assertEquals(BoundType.CLOSED, r.lowerBoundType());
assertEquals(BoundType.CLOSED, r.upperBoundType());
}
public void testDefaultBoundTypeNoBoundTypeInformedWithClosedConfigured() throws Exception
{
String json = "{\"lowerEndpoint\": 2, \"upperEndpoint\": 3}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(2), r.lowerEndpoint());
assertEquals(Integer.valueOf(3), r.upperEndpoint());
assertEquals(BoundType.CLOSED, r.lowerBoundType());
assertEquals(BoundType.CLOSED, r.upperBoundType());
}
public void testDefaultBoundTypeOnlyLowerBoundTypeInformedWithClosedConfigured() throws Exception
{
String json = "{\"lowerEndpoint\": 2, \"lowerBoundType\": \"OPEN\", \"upperEndpoint\": 3}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(2), r.lowerEndpoint());
assertEquals(Integer.valueOf(3), r.upperEndpoint());
assertEquals(BoundType.OPEN, r.lowerBoundType());
assertEquals(BoundType.CLOSED, r.upperBoundType());
}
public void testDefaultBoundTypeOnlyUpperBoundTypeInformedWithClosedConfigured() throws Exception
{
String json = "{\"lowerEndpoint\": 1, \"upperEndpoint\": 3, \"upperBoundType\": \"OPEN\"}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(1), r.lowerEndpoint());
assertEquals(Integer.valueOf(3), r.upperEndpoint());
assertEquals(BoundType.CLOSED, r.lowerBoundType());
assertEquals(BoundType.OPEN, r.upperBoundType());
}
public void testDefaultBoundTypeBothBoundTypesOpenWithClosedConfigured() throws Exception
{
String json = "{\"lowerEndpoint\": 1, \"lowerBoundType\": \"OPEN\", \"upperEndpoint\": 3, \"upperBoundType\": \"OPEN\"}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(1), r.lowerEndpoint());
assertEquals(Integer.valueOf(3), r.upperEndpoint());
assertEquals(BoundType.OPEN, r.lowerBoundType());
assertEquals(BoundType.OPEN, r.upperBoundType());
}
public void testDefaultBoundTypeBothBoundTypesClosedWithOpenConfigured() throws Exception
{
String json = "{\"lowerEndpoint\": 12, \"lowerBoundType\": \"CLOSED\", \"upperEndpoint\": 33, \"upperBoundType\": \"CLOSED\"}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(12), r.lowerEndpoint());
assertEquals(Integer.valueOf(33), r.upperEndpoint());
assertEquals(BoundType.CLOSED, r.lowerBoundType());
assertEquals(BoundType.CLOSED, r.upperBoundType());
}
public void testSnakeCaseNamingStrategy() throws Exception
{
String json = "{\"lower_endpoint\": 12, \"lower_bound_type\": \"CLOSED\", \"upper_endpoint\": 33, \"upper_bound_type\": \"CLOSED\"}";
GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.build();
@SuppressWarnings("unchecked")
Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);
assertEquals(Integer.valueOf(12), r.lowerEndpoint());
assertEquals(Integer.valueOf(33), r.upperEndpoint());
assertEquals(BoundType.CLOSED, r.lowerBoundType());
assertEquals(BoundType.CLOSED, r.upperBoundType());
}
@Override
public ObjectMapper get()
{
ObjectMapper mapper = objectMapper;
if (mapper == null) {
final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector();
AnnotationIntrospector defaultAI = new JacksonAnnotationIntrospector();
MapperBuilder<?,?> builder = JsonMapper.builder()
.injectableValues(new GuiceInjectableValues(injector))
.annotationIntrospector(new AnnotationIntrospectorPair(guiceIntrospector, defaultAI))
.addModules(modulesToAdd);
for (Provider<? extends Module> provider : providedModules) {
builder = builder.addModule(provider.get());
}
mapper = builder.build();
/*
} else {
// 05-Feb-2017, tatu: _Should_ be fine, considering instances are now (3.0) truly immutable.
// But if this turns out to be problematic, may need to consider addition of `copy()`
// back in databind
mapper = mapper.copy();
*/
}
return mapper;
}
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception
{
bundleContext = mock(BundleContext.class);
doThrow(new InvalidSyntaxException("", "")).when(bundleContext).createFilter(anyString());
Filter filter = mock(Filter.class);
when(filter.toString()).thenReturn(OSGI_FILTER);
doReturn(filter).when(bundleContext).createFilter(OSGI_FILTER);
when(bundleContext.getServiceReferences(eq(Service.class.getName()), anyString())).thenReturn(new ServiceReference[]{mock(ServiceReference.class)});
when(bundleContext.getService(any(ServiceReference.class))).thenReturn(mock(Service.class));
mapper = JsonMapper.builder()
.addModule(new OsgiJacksonModule(bundleContext))
.build();
}
public void testIdWithJacksonRules() throws Exception
{
String expected = "[{\"id\":11,\"username\":\"11\",\"email\":\"[email protected]\","
+"\"department\":{\"id\":9,\"name\":\"department9\",\"employees\":["
+"11,{\"id\":22,\"username\":\"22\",\"email\":\"[email protected]\","
+"\"department\":9}]}},22,{\"id\":33,\"username\":\"33\",\"email\":\"[email protected]\",\"department\":null}]";
ObjectMapper mapper = JsonMapper.builder()
// true -> ignore XmlIDREF annotation
.annotationIntrospector(new JaxbAnnotationIntrospector(true))
.build();
// first, with default settings (first NOT as id)
List<User> users = getUserList();
String json = mapper.writeValueAsString(users);
assertEquals(expected, json);
List<User> result = mapper.readValue(json, new TypeReference<List<User>>() { });
assertEquals(3, result.size());
assertEquals(Long.valueOf(11), result.get(0).id);
assertEquals(Long.valueOf(22), result.get(1).id);
assertEquals(Long.valueOf(33), result.get(2).id);
}
public void testIdWithJaxbRules() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
// but then also variant where ID is ALWAYS used for XmlID / XmlIDREF
.annotationIntrospector(new JaxbAnnotationIntrospector())
.build();
List<User> users = getUserList();
final String json = mapper.writeValueAsString(users);
String expected = "[{\"id\":11,\"username\":\"11\",\"email\":\"[email protected]\",\"department\":9}"
+",{\"id\":22,\"username\":\"22\",\"email\":\"[email protected]\",\"department\":9}"
+",{\"id\":33,\"username\":\"33\",\"email\":\"[email protected]\",\"department\":null}]";
assertEquals(expected, json);
// However, there is no way to resolve those back, without some external mechanism...
}
public void testWithCtorAndDelegate() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
.injectableValues(new InjectableValues.Std()
.addValue(String.class, "Pooka"))
.addModule(new AfterburnerModule())
.build();
CtorBean711 bean = null;
try {
bean = mapper.readValue("38", CtorBean711.class);
} catch (JsonMappingException e) {
fail("Did not expect problems, got: "+e.getMessage());
}
assertEquals(38, bean.age);
assertEquals("Pooka", bean.name);
}
public void testWithFactoryAndDelegate() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
.injectableValues(new InjectableValues.Std()
.addValue(String.class, "Fygar"))
.addModule(new AfterburnerModule())
.build();
FactoryBean711 bean = null;
try {
bean = mapper.readValue("38", FactoryBean711.class);
} catch (JsonMappingException e) {
fail("Did not expect problems, got: "+e.getMessage());
}
assertEquals(38, bean.age);
assertEquals("Fygar", bean.name1);
assertEquals("Fygar", bean.name2);
}
public void testUnwrapSingleArray() throws Exception
{
final ObjectMapper mapper = JsonMapper.builder()
.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.addModule(new AfterburnerModule())
.build();
final Integer intValue = mapper.readValue("[ 1 ]", Integer.class);
assertEquals(Integer.valueOf(1), intValue);
final String strValue = mapper.readValue("[ \"abc\" ]", String.class);
assertEquals("abc", strValue);
// and then via POJO. First, array of POJOs
IntBean b1 = mapper.readValue(aposToQuotes("[{ 'value' : 123 }]"), IntBean.class);
assertNotNull(b1);
assertEquals(123, b1.value);
// and then array of ints within POJO
IntBean b2 = mapper.readValue(aposToQuotes("{ 'value' : [ 123 ] }"), IntBean.class);
assertNotNull(b2);
assertEquals(123, b2.value);
}
public static void main(String[] args) throws Exception
{
if (args.length != 0) {
System.err.println("Usage: java ...");
System.exit(1);
}
ObjectMapper vanilla = new ObjectMapper();
ObjectMapper burnt = JsonMapper.builder()
.addModule(new AfterburnerModule())
.build();
/*
TestPojo input = new TestPojo(1245, -99, "Billy-Bob",
new Value(27, 116));
new ManualDatabindPerf().test(vanilla, burnt, input, TestPojo.class);
*/
MediaItem media = MediaItem.buildItem();
new ManualDatabindPerf().test(vanilla, burnt, media, MediaItem.class);
}
public void testPlainGetAndSet() throws Exception
{
// First, simple attempt fails
try {
MAPPER.readValue("{}", JustGetAndSet.class);
fail("Should not pass");
} catch (JsonMappingException e) {
verifyException(e, "Unrecognized abstract method");
}
// but can make work with config:
AbstractTypeMaterializer mat = new AbstractTypeMaterializer();
mat.disable(AbstractTypeMaterializer.Feature.FAIL_ON_UNMATERIALIZED_METHOD);
ObjectMapper mapper = JsonMapper.builder()
.addModule(new MrBeanModule(mat))
.build();
JustGetAndSet value = mapper.readValue("{}", JustGetAndSet.class);
assertNotNull(value);
}
/**
* Test to verify that materializer will by default create exception-throwing methods
* for "unknown" abstract methods
*/
public void testPartialBean() throws Exception
{
AbstractTypeMaterializer mat = new AbstractTypeMaterializer();
// ensure that we will only get deferred error methods
mat.disable(AbstractTypeMaterializer.Feature.FAIL_ON_UNMATERIALIZED_METHOD);
ObjectMapper mapper = JsonMapper.builder()
.addModule(new MrBeanModule(mat))
.build();
PartialBean bean = mapper.readValue("{\"ok\":true}", PartialBean.class);
assertNotNull(bean);
assertTrue(bean.isOk());
// and then exception
try {
bean.foobar();
} catch (UnsupportedOperationException e) {
verifyException(e, "Unimplemented method 'foobar'");
}
}
@Test
void shouldSerializeWithoutAutoDetect() throws JsonProcessingException {
final JsonMapper mapper = JsonMapper.builder()
.disable(MapperFeature.AUTO_DETECT_FIELDS)
.disable(MapperFeature.AUTO_DETECT_GETTERS)
.disable(MapperFeature.AUTO_DETECT_IS_GETTERS)
.addModule(new ProblemModule())
.addModule(new ConstraintViolationProblemModule())
.build();
final Violation violation = new Violation("bob", "was missing");
final ConstraintViolationProblem unit = new ConstraintViolationProblem(BAD_REQUEST, singletonList(violation));
with(mapper.writeValueAsString(unit))
.assertThat("status", is(400))
.assertThat("type", is(ConstraintViolationProblem.TYPE_VALUE))
.assertThat("title", is("Constraint Violation"))
.assertThat("violations", hasSize(1))
.assertThat("violations.*.field", contains("bob"))
.assertThat("violations.*.message", contains("was missing"));
}
@BeforeClass
public static void setUp() {
// Initialize object mapper for testing. With this configuration we save a lot of quotes and escaping when creating JSON strings.
mapper = JsonMapper.builder()
.enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES)
.enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
.build();
// Initialize validator for testing including custom mappings.
validator = Validation.byDefaultProvider()
.configure()
.addMapping(AbstractRequestTest.class.getClassLoader().getResourceAsStream(VALIDATION_MAPPINGS))
.buildValidatorFactory()
.getValidator();
}
private static ObjectMapper defaultMapper() {
final ObjectMapper objectMapper = JsonMapper.builder()
.serializationInclusion(JsonInclude.Include.NON_EMPTY)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS, false)
.build()
.registerModule(new Jdk8Module())
.registerModule(new InterledgerModule(Encoding.BASE64));
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
return objectMapper;
}
@Test
public void testDeserializationWithTypeInfo01() throws Exception
{
Period period = Period.of(5, 1, 12);
ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.addMixIn(TemporalAmount.class, MockObjectConfiguration.class)
.build();
TemporalAmount value = mapper.readValue(
"[\"" + Period.class.getName() + "\",\"" + period.toString() + "\"]", TemporalAmount.class
);
assertTrue("The value should be a Period.", value instanceof Period);
assertEquals("The value is not correct.", period, value);
}
@Before
public void setUp()
{
MAPPER = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
}
@Test
public void testSerializationWithTypeInfo01() throws Exception
{
final ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class)
.build();
MonthDay monthDay = MonthDay.of(Month.NOVEMBER, 5);
String value = mapper.writeValueAsString(monthDay);
assertEquals("The value is not correct.", "[\"" + MonthDay.class.getName() + "\",\"--11-05\"]", value);
}
@Test
public void testDeserializationWithTypeInfo01() throws Exception
{
final ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class)
.build();
MonthDay monthDay = MonthDay.of(Month.NOVEMBER, 5);
TemporalAccessor value = mapper.readValue("[\"" + MonthDay.class.getName() + "\",\"--11-05\"]", TemporalAccessor.class);
assertEquals("The value is not correct.", monthDay, value);
}
private String serializeWith(ZonedDateTime zonedDateTime, DateTimeFormatter f) throws Exception {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SimpleModule().addSerializer(
new ZonedDateTimeSerializer(f)))
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
return mapper.writeValueAsString(zonedDateTime);
}
private String serializeWith(LocalDate date, DateTimeFormatter f) throws Exception {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SimpleModule()
.addSerializer(new LocalDateSerializer(f)))
.build();
return mapper.writeValueAsString(date);
}
private LocalDate deserializeWith(String json, DateTimeFormatter f) throws Exception {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SimpleModule()
.addDeserializer(LocalDate.class, new LocalDateDeserializer(f)))
.build();
return mapper.readValue("\"" + json + "\"", LocalDate.class);
}
private String serializeWith(LocalTime dateTime, DateTimeFormatter f) throws Exception {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SimpleModule()
.addSerializer(new LocalTimeSerializer(f)))
.build();
return mapper.writeValueAsString(dateTime);
}
private LocalTime deserializeWith(String json, DateTimeFormatter f) throws Exception {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new SimpleModule()
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(f)))
.build();
return mapper.readValue("\"" + json + "\"", LocalTime.class);
}