List of usage examples for com.fasterxml.jackson.databind ObjectMapper writerWithType
public ObjectWriter writerWithType(JavaType rootType)
From source file:org.mashti.jetson.util.JsonGeneratorUtil.java
/** * Writes the given {@code values} as a JSON array with the given field name and serialises each value as a provided type. * An {@link ObjectMapper} must be present as the {@code generator}'s {@link JsonGenerator#getCodec() codec}. * For each value in the given {@code values}, a type must be provided under the same index in {@code value_types}. * This method supports parameterised types. * * @param generator the JSON generator/* w ww. j a v a 2s . com*/ * @param field_name the field name of the JSON array * @param value_types the types of the values * @param values the values * @throws IOException Signals that an I/O exception has occurred. */ public static void writeValuesAs(final JsonGenerator generator, final String field_name, final Type[] value_types, final Object[] values) throws IOException { generator.writeArrayFieldStart(field_name); if (values != null && values.length > 0) { final ObjectMapper mapper = (ObjectMapper) generator.getCodec(); int i = 0; for (final Object value : values) { final Type value_type = value_types[i++]; final ObjectWriter writer = mapper.writerWithType(JsonParserUtil.toTypeReference(value_type)); writer.writeValue(generator, value); } } generator.writeEndArray(); }
From source file:org.n52.web.BaseController.java
private void writeExceptionResponse(WebException e, HttpServletResponse response, HttpStatus status) { if (status == INTERNAL_SERVER_ERROR) { LOGGER.error("An exception occured.", e); } else {//from w ww . j a va2 s .co m LOGGER.debug("An exception occured.", e); } // TODO consider using a 'suppress_response_codes=true' parameter and always return 200 OK response.setStatus(status.value()); response.setContentType(APPLICATION_JSON.getMimeType()); ObjectMapper objectMapper = createObjectMapper(); ObjectWriter writer = objectMapper.writerWithType(ExceptionResponse.class); ExceptionResponse exceptionResponse = createExceptionResponse(e, status); try { writer.writeValue(response.getOutputStream(), exceptionResponse); } catch (IOException ioe) { LOGGER.error("Could not process error message.", e); } }
From source file:com.feedzai.fos.api.CategoricalAttributeTest.java
@Test public void testJackson() throws Exception { List<Attribute> attributes = new ArrayList<>(); attributes.add(field);//from w ww . j av a 2 s .c o m ObjectMapper mapper = new ObjectMapper(); TypeReference<List<Attribute>> typeReference = new TypeReference<List<Attribute>>() { }; String result = mapper.writerWithType(typeReference).writeValueAsString(attributes); List<Attribute> deserialized = mapper.readValue(result, typeReference); assertEquals(attributes.size(), deserialized.size()); CategoricalAttribute extracted = (CategoricalAttribute) deserialized.get(0); assertEquals(field.getName(), extracted.getName()); assertEquals(field.getCategoricalInstances(), extracted.getCategoricalInstances()); }
From source file:test.com.wealdtech.jackson.modules.WIDModuleTest.java
@Test public void testObjectMap() { final ObjectMapper mapper = WealdMapper.getMapper().copy().enableDefaultTyping(); final Map<String, Object> map = Maps.newHashMap(); map.put("test1", new Date()); map.put("test2", new InetSocketAddress(10)); try {// w w w . j ava 2 s. c om final String ser = mapper.writerWithType(Map.class).writeValueAsString(map); final Map<String, Object> deser = this.mapper.readValue(ser, new TypeReference<Map<String, Object>>() { }); assertTrue(deser.get("test1") instanceof Date); assertTrue(deser.get("test2") instanceof InetSocketAddress); } catch (final IOException e) { fail("Failed", e); } }
From source file:com.proofpoint.http.client.SmileBodyGenerator.java
public static <T> SmileBodyGenerator<T> smileBodyGenerator(JsonCodec<T> jsonCodec, T instance) { ObjectMapper objectMapper = OBJECT_MAPPER_SUPPLIER.get(); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator jsonGenerator;// w w w. j a va 2 s . com try { jsonGenerator = new SmileFactory().createGenerator(out); } catch (IOException e) { throw propagate(e); } Type genericType = jsonCodec.getType(); // 04-Mar-2010, tatu: How about type we were given? (if any) JavaType rootType = null; if (genericType != null && instance != null) { // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root // type since it prevents polymorphic type serialization. Since we really // just need this for generics, let's only use generic type if it's truly // generic. if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type' // This is still not exactly right; should root type be further // specialized with 'value.getClass()'? Let's see how well this works before // trying to come up with more complete solution. rootType = objectMapper.getTypeFactory().constructType(genericType); // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where // type degenerates back into "Object.class" (as is the case with plain TypeVariable, // for example), and not use that. // if (rootType.getRawClass() == Object.class) { rootType = null; } } } try { if (rootType != null) { objectMapper.writerWithType(rootType).writeValue(jsonGenerator, instance); } else { objectMapper.writeValue(jsonGenerator, instance); } } catch (IOException e) { throw new IllegalArgumentException( String.format("%s could not be converted to SMILE", instance.getClass().getName()), e); } return new SmileBodyGenerator<>(out.toByteArray()); }