public void testJsonFactoryLinkage() { // first, implicit factory, giving implicit linkage assertSame(MAPPER, MAPPER.getFactory().getCodec()); // and then explicit factory, which should also be implicitly linked JsonFactory f = new JsonFactory(); ObjectMapper m = new ObjectMapper(f); assertSame(f, m.getFactory()); assertSame(m, f.getCodec()); }
// [Issue#28]: ObjectMapper.copy() public void testCopy() throws Exception { ObjectMapper m = new ObjectMapper(); assertTrue(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); InjectableValues inj = new InjectableValues.Std(); m.setInjectableValues(inj); assertFalse(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); m.enable(JsonParser.Feature.ALLOW_COMMENTS); assertTrue(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); // // First: verify that handling of features is decoupled: ObjectMapper m2 = m.copy(); assertFalse(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m2.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertTrue(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertSame(inj, m2.getInjectableValues()); // but should NOT change the original assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); // nor vice versa: assertFalse(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); m.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); assertTrue(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); // // Also, underlying JsonFactory instances should be distinct assertNotSame(m.getFactory(), m2.getFactory()); // [Issue#122]: Need to ensure mix-ins are not shared assertEquals(0, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(0, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); m.addMixIn(String.class, Integer.class); assertEquals(1, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(1, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); // [Issue#913]: Ensure JsonFactory Features copied assertTrue(m2.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); }
@GET("/backend/aggregate/points") String getPoints(String content) throws IOException { logger.debug("getPoints(): content={}", content); PointsRequest request = ObjectMappers.readRequiredValue(mapper, content, PointsRequest.class); List<AggregatePoint> points = aggregateDao.readAggregates(request.getFrom(), request.getTo()); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); jg.writeStartObject(); jg.writeArrayFieldStart("points"); for (AggregatePoint point : points) { jg.writeStartArray(); jg.writeNumber(point.getCaptureTime()); long durationAverage; if (point.getTraceCount() == 0) { durationAverage = 0; } else { durationAverage = point.getDurationTotal() / point.getTraceCount(); } jg.writeNumber(durationAverage / 1000000000.0); jg.writeNumber(point.getTraceCount()); jg.writeEndArray(); } jg.writeEndArray(); jg.writeNumberField("fixedAggregateIntervalSeconds", fixedAggregateIntervalSeconds); jg.writeEndObject(); jg.close(); return sb.toString(); }
public static String objectToJson(Object object) { JsonGenerator jsonGenerator = null; ObjectMapper objectMapper = new ObjectMapper(); ByteArrayOutputStream out = null; String json = null; try { try { String jsonStr = ""; out = new ByteArrayOutputStream(); jsonGenerator = objectMapper.getFactory().createGenerator(out, JsonEncoding.UTF8); jsonGenerator.writeObject(object); json = new String(out.toByteArray(), Charset.forName("UTF-8")); out.toString(); System.out.println(json); } finally { if (jsonGenerator != null) { jsonGenerator.flush(); } if (!jsonGenerator.isClosed()) { jsonGenerator.close(); } if (out != null) { out.close(); } jsonGenerator = null; objectMapper = null; } } catch (Exception e) { } return json; }
@RequestMapping(value = "/contacts/email/{email}", method = GET) public String getContactByEmail(@PathVariable String email) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); ContactDto contact = contactService.getByEmail(email); return mapper.writeValueAsString(contact); }
/** * @param json A valid JSON stream, may be <code>null</code>. * @return The {@link DataSetMetadata} instance parsed from stream or <code>null</code> if * parameter is null. If stream is empty, also returns <code>null</code>. */ public DataSet from(InputStream json) { try { final ObjectMapper mapper = builder.build(); JsonParser parser = mapper.getFactory().createParser(json); return mapper.readerFor(DataSet.class).readValue(parser); } catch (Exception e) { throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_JSON, e); } }
public void writeToWriter(Writer writer, Object input) { final ObjectMapper objectMapper = dataFormat.getObjectMapper(); final JsonFactory factory = objectMapper.getFactory(); try { JsonGenerator generator = factory.createGenerator(writer); objectMapper.writeTree(generator, (JsonNode) input); } catch (IOException e) { throw LOG.unableToWriteJsonNode(e); } }
@SuppressWarnings("unchecked") public static Lexer getByFullName(String pack, String sub, String name) throws ResolutionException { String fullname = name; if (!pack.isEmpty()) { if (!sub.isEmpty()) { fullname = pack + "." + sub + "." + fullname; } else { fullname = pack + "." + fullname; } } // Try cache Lexer lexer = lexers.get(fullname); if (lexer != null) return lexer; try { return (Lexer) Jygments.class.getClassLoader().loadClass(fullname).newInstance(); } catch (InstantiationException x) { } catch (IllegalAccessException x) { } catch (ClassNotFoundException x) { } InputStream stream = Util.getJsonFile(pack, sub, name, fullname); if (stream != null) { try { String converted = Util.rejsonToJson(stream); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.getFactory().configure(JsonParser.Feature.ALLOW_COMMENTS, true); Map<String, Object> json = objectMapper.readValue(converted, HashMap.class); Object className = json.get("class"); if (className == null) className = ""; lexer = getByName(className.toString()); lexer.addJson(json); lexer.resolve(); if (lexer != null) { // Cache it Lexer existing = lexers.putIfAbsent(fullname, lexer); if (existing != null) lexer = existing; } return lexer; } catch (JsonParseException x) { throw new ResolutionException(x); } catch (JsonMappingException x) { throw new ResolutionException(x); } catch (IOException x) { throw new ResolutionException(x); } } return null; }
@Override public void initInputStream(InputStream is) throws InputParserException { try { inputStream = is; parser = mapper.getFactory().createParser(is); } catch (JsonParseException e) { throw new InputParserException("Can't initialize the stream to read activities.", e); } catch (IOException e) { throw new InputParserException("I/O Exception while initializing the parser", e); } }
public static String toPrettyString(byte[] bytes) { StringWriter w = new StringWriter(); try { JSON_MAPPER .getFactory() .createGenerator(w) .useDefaultPrettyPrinter() .writeTree(JSON_MAPPER.readTree(bytes)); return w.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void writeJSONViaLowerlevelLibs() throws IOException { final StringWriter writer = new StringWriter(); final ObjectMapper mapper = new ObjectMapper(); final JsonGenerator jgen = mapper.getFactory().createGenerator(writer); jgen.writeStartObject(); jgen.writeStringField( "odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer"); jgen.writeStringField("*****@*****.**", "Edm.String"); jgen.writeStringField("Name", "A name"); jgen.writeStringField("*****@*****.**", "Edm.Int32"); jgen.writeNumberField("CustomerId", 0); jgen.writeArrayFieldStart("BackupContactInfo"); jgen.writeStartObject(); jgen.writeArrayFieldStart("AlternativeNames"); jgen.writeString("myname"); jgen.writeEndArray(); jgen.writeArrayFieldStart("EmailBag"); jgen.writeString("*****@*****.**"); jgen.writeEndArray(); jgen.writeObjectFieldStart("ContactAlias"); jgen.writeStringField( "odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases"); jgen.writeArrayFieldStart("AlternativeNames"); jgen.writeString("myAlternativeName"); jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndObject(); jgen.writeEndArray(); jgen.writeEndObject(); jgen.flush(); assertFalse(writer.toString().isEmpty()); }
public static String Object2Json(Object o) { try { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); JsonFactory factory = mapper.getFactory(); JsonGenerator gen = factory.createGenerator(writer); mapper.writeValue(gen, o); gen.close(); String json = writer.toString(); writer.close(); return json; } catch (Exception e) { e.printStackTrace(); return null; } }
@Test public void should_iterate_row_with_metadata() throws IOException { // given String[] columnNames = new String[] { "id", "firstname", "lastname", "state", "registration", "city", "birth", "nbCommands", "avgAmount" }; final InputStream input = this.getClass().getResourceAsStream("dataSetRowMetadata.json"); final ObjectMapper mapper = builder.build(); try (JsonParser parser = mapper.getFactory().createParser(input)) { final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser); final Iterator<DataSetRow> iterator = dataSet.getRecords().iterator(); List<ColumnMetadata> actualColumns = new ArrayList<>(); int recordCount = 0; while (iterator.hasNext()) { final DataSetRow next = iterator.next(); actualColumns = next.getRowMetadata().getColumns(); assertThat(actualColumns, not(empty())); recordCount++; } // then assertEquals(10, recordCount); for (int i = 0; i < actualColumns.size(); i++) { final ColumnMetadata column = actualColumns.get(i); assertEquals(columnNames[i], column.getId()); } } catch (Exception e) { throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_JSON, e); } }
protected void writeJson(ResponseWrapper response, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType()); ObjectMapper mapper = new ObjectMapper(); // Add support for jackson mixins JsonMixin[] jsonMixins = response.getJsonResponse().mixins(); for (JsonMixin jsonMixin : jsonMixins) { mapper.addMixIn(jsonMixin.target(), jsonMixin.mixin()); } JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(outputMessage.getBody(), encoding); try { mapper.writeValue(jsonGenerator, response.getOriginalResponse()); } catch (IOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
/** * Serializes this processing result as JSON to the provided <code>writer</code>. Documents, * clusters and other attributes can be included or skipped in the output as requested. * * @param writer the writer to serialize this processing result to. The writer will * <strong>not</strong> be closed. * @param callback JavaScript function name in which to wrap the JSON response or <code>null * </code>. * @param indent if <code>true</code>, the output JSON will be pretty-printed * @param saveDocuments if <code>false</code>, documents will not be serialized. * @param saveClusters if <code>false</code>, clusters will not be serialized * @param saveOtherAttributes if <code>false</code>, other attributes will not be serialized * @throws IOException in case of any problems with serialization */ public void serializeJson( Writer writer, String callback, boolean indent, boolean saveDocuments, boolean saveClusters, boolean saveOtherAttributes) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); mapper.enable(SerializationFeature.INDENT_OUTPUT); if (StringUtils.isNotBlank(callback)) { writer.write(callback + "("); } final Map<String, Object> attrs = prepareAttributesForSerialization(saveDocuments, saveClusters, saveOtherAttributes); mapper.writeValue(writer, attrs); if (StringUtils.isNotBlank(callback)) { writer.write(");"); } }
public static <T> T readObject(final String in, final Class<T> type) throws IOException { final JsonParser parser = mapper .getFactory() .createJsonParser( new StringReader(in) { @Override public String toString() { return "message"; } // overridden for better source in error message }); final T result = mapper.readValue(parser, type); boolean trailingContent; try { trailingContent = parser.nextToken() != null; } catch (IOException e) { trailingContent = true; } if (trailingContent) { throw new IOException("Unexpected trailing content at " + parser.getCurrentLocation()); } return result; }
@Test public void testCompleteSetup() { NopAnnotationIntrospector annotationIntrospector = NopAnnotationIntrospector.instance; ObjectMapper objectMapper = new ObjectMapper(); assertTrue(this.factory.isSingleton()); assertEquals(ObjectMapper.class, this.factory.getObjectType()); Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<Class<?>, JsonDeserializer<?>>(); deserializers.put(Date.class, new DateDeserializer()); factory.setObjectMapper(objectMapper); JsonSerializer serializer1 = new ClassSerializer(); JsonSerializer serializer2 = new NumberSerializer(); factory.setSerializers(serializer1); factory.setSerializersByType( Collections.<Class<?>, JsonSerializer<?>>singletonMap(Boolean.class, serializer2)); factory.setDeserializersByType(deserializers); factory.setAnnotationIntrospector(annotationIntrospector); this.factory.setFeaturesToEnable( SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.UNWRAP_ROOT_VALUE, JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS); this.factory.setFeaturesToDisable( MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_FIELDS, JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonGenerator.Feature.QUOTE_FIELD_NAMES); assertFalse(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertFalse(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); this.factory.setSerializationInclusion(JsonInclude.Include.NON_NULL); this.factory.afterPropertiesSet(); assertTrue(objectMapper == this.factory.getObject()); assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertTrue( serializers.findSerializer(null, SimpleType.construct(Class.class), null) == serializer1); assertTrue( serializers.findSerializer(null, SimpleType.construct(Boolean.class), null) == serializer2); assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); assertTrue( annotationIntrospector == objectMapper.getSerializationConfig().getAnnotationIntrospector()); assertTrue( annotationIntrospector == objectMapper.getDeserializationConfig().getAnnotationIntrospector()); assertTrue( objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertTrue( objectMapper .getDeserializationConfig() .isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertTrue( objectMapper .getFactory() .isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse( objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); assertTrue( objectMapper.getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_NULL); }
@SuppressWarnings("resource") public void writeJsonResponse( HttpServletResponse response, Object responseObject, Class<?> jsonView, boolean streamResponse, boolean isMultipart) throws IOException, JsonGenerationException, JsonMappingException { ObjectMapper objectMapper = configurationService.getJsonHandler().getMapper(); if (isMultipart) { response.setContentType(RouterController.TEXT_HTML.toString()); response.setCharacterEncoding(RouterController.TEXT_HTML.getCharSet().name()); ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET)); String responseJson; if (jsonView == null) { responseJson = objectMapper.writeValueAsString(responseObject); } else { responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject); } responseJson = responseJson.replace(""", "\\""); bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET)); bos.write("</textarea></body></html>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET)); response.setContentLength(bos.size()); FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream()); } else { response.setContentType(APPLICATION_JSON.toString()); response.setCharacterEncoding(APPLICATION_JSON.getCharSet().name()); ServletOutputStream outputStream = response.getOutputStream(); if (!streamResponse) { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); JsonGenerator jsonGenerator = objectMapper.getFactory().createJsonGenerator(bos, JsonEncoding.UTF8); if (jsonView == null) { objectMapper.writeValue(jsonGenerator, responseObject); } else { objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject); } response.setContentLength(bos.size()); outputStream.write(bos.toByteArray()); jsonGenerator.close(); } else { JsonGenerator jsonGenerator = objectMapper.getFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8); if (jsonView == null) { objectMapper.writeValue(jsonGenerator, responseObject); } else { objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject); } jsonGenerator.close(); } outputStream.flush(); } }