public static String marshalJson(CASServiceResponse serviceResponse) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //Force newlines to be LF (default is system dependent) DefaultPrettyPrinter printer = new DefaultPrettyPrinter() .withObjectIndenter(new DefaultIndenter(" ", "\n")); //create wrapper node Map<String, Object> casModel = new HashMap<>(); casModel.put("serviceResponse", serviceResponse); try { return mapper.writer(printer).writeValueAsString(casModel); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }
public void testCustomSeparatorsWithPP() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(ObjectWriteContext.empty(), sw); gen.setPrettyPrinter(new DefaultPrettyPrinter().withSeparators(Separators.createDefaultInstance() .withObjectFieldValueSeparator('=') .withObjectEntrySeparator(';') .withArrayValueSeparator('|'))); _writeTestDocument(gen); gen.close(); assertEquals("[ 3| \"abc\"| [ true ]| {" + DefaultIndenter.SYS_LF + " \"f\" = null;" + DefaultIndenter.SYS_LF + " \"f2\" = null" + DefaultIndenter.SYS_LF + "} ]", sw.toString()); }
public void testCustomSeparatorsWithPPWithoutSpaces() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(ObjectWriteContext.empty(), sw); gen.setPrettyPrinter(new DefaultPrettyPrinter().withSeparators(Separators.createDefaultInstance() .withObjectFieldValueSeparator('=') .withObjectEntrySeparator(';') .withArrayValueSeparator('|')) .withoutSpacesInObjectEntries()); _writeTestDocument(gen); gen.close(); assertEquals("[ 3| \"abc\"| [ true ]| {" + DefaultIndenter.SYS_LF + " \"f\"=null;" + DefaultIndenter.SYS_LF + " \"f2\"=null" + DefaultIndenter.SYS_LF + "} ]", sw.toString()); }
public static ObjectMapper objectMapper() { return new ObjectMapper() // Property visibility .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) // Property naming and order .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); }
/** * Exports data to a {@link Writer}. * * @param writer the writer * @throws NitriteIOException if there is any error while writing the data. */ public void exportTo(Writer writer) { JsonGenerator generator; try { generator = jsonFactory.createGenerator(writer); generator.setPrettyPrinter(new DefaultPrettyPrinter()); } catch (IOException ioe) { throw new NitriteIOException(EXPORT_WRITER_ERROR, ioe); } NitriteJsonExporter jsonExporter = new NitriteJsonExporter(db); jsonExporter.setGenerator(generator); jsonExporter.setOptions(options); try { jsonExporter.exportData(); } catch (IOException | ClassNotFoundException e) { throw new NitriteIOException(EXPORT_WRITE_ERROR, e); } }
/** * Creates a new EclipseParser * * @param sourceFile String of source file to read * @param outJ JSON parsed out * @throws IOException when file can't be opened or errors in reading/writing */ public EclipseParser(String sourceFile, PrintStream outJ, boolean prettyprint) throws IOException { File file = new File(sourceFile); final BufferedReader reader = new BufferedReader(new FileReader(file)); char[] source = IOUtils.toCharArray(reader); reader.close(); this.parser = ASTParser.newParser(AST.JLS8); parser.setSource(source); parser.setKind(ASTParser.K_COMPILATION_UNIT); final JsonFactory jsonF = new JsonFactory(); jG = jsonF.createGenerator(outJ); if (prettyprint) { jG.setPrettyPrinter(new DefaultPrettyPrinter()); mapper.enable(SerializationFeature.INDENT_OUTPUT); } mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); SimpleModule module = new SimpleModule(); module.addSerializer(ASTNode.class, new NodeSerializer()); mapper.registerModule(module); }
@Nonnull private static ObjectWriter createJsonWriter(final boolean prettyPrint) { final ObjectMapper mapper = new ObjectMapper(); if (!prettyPrint) { return mapper.writer(); } final DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(" ", DefaultIndenter.SYS_LF); final DefaultPrettyPrinter printer = new DefaultPrettyPrinter(""); printer.withoutSpacesInObjectEntries(); printer.indentObjectsWith(indenter); printer.indentArraysWith(indenter); return mapper.writer(printer); }
@Test public void serializationEntityTypeTest() throws JsonProcessingException { ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); EntityType entityType = new EntityType(); Map<String,AttributeType> attrs = new HashMap<>(); AttributeType tempAttribute = new AttributeType("urn:phenomenum:temperature"); attrs.put("temperature", tempAttribute); AttributeType humidityAttribute = new AttributeType("percentage"); attrs.put("humidity", humidityAttribute); AttributeType pressureAttribute = new AttributeType("null"); attrs.put("pressure", pressureAttribute); entityType.setAttrs(attrs); entityType.setCount(7); String json = writer.writeValueAsString(entityType); assertEquals(jsonString, json); }
@Test public void serializationRegistrationTest() throws JsonProcessingException, MalformedURLException { ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); Registration registration = new Registration("abcde", new URL("http://localhost:1234")); registration.setDuration("PT1M"); SubjectEntity subjectEntity = new SubjectEntity(); subjectEntity.setType(Optional.of("Room")); SubjectRegistration subjectRegistration = new SubjectRegistration(Collections.singletonList(subjectEntity), Collections.singletonList("humidity")); registration.setSubject(subjectRegistration); String json = writer.writeValueAsString(registration); String jsonString ="{\n" + " \"id\" : \"abcde\",\n" + " \"subject\" : {\n" + " \"entities\" : [ {\n" + " \"type\" : \"Room\"\n" + " } ],\n" + " \"attributes\" : [ \"humidity\" ]\n" + " },\n" + " \"callback\" : \"http://localhost:1234\",\n" + " \"duration\" : \"PT1M\"\n" + "}"; assertEquals(jsonString, json); }
@Test public void serializationEntityTest() throws JsonProcessingException { ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); Entity entity = new Entity("Bcn-Welt", "Room"); HashMap<String,Attribute> attributes = new HashMap<String, Attribute>(); Attribute tempAttribute = new Attribute(21.7); attributes.put("temperature", tempAttribute); Attribute humidityAttribute = new Attribute(60); attributes.put("humidity", humidityAttribute); entity.setAttributes(attributes); String json = writer.writeValueAsString(entity); String jsonString = "{\n" + " \"id\" : \"Bcn-Welt\",\n" + " \"type\" : \"Room\",\n" + " \"temperature\" : {\n" + " \"value\" : 21.7,\n" + " \"metadata\" : { }\n" + " },\n" + " \"humidity\" : {\n" + " \"value\" : 60,\n" + " \"metadata\" : { }\n" + " }\n" + "}"; assertEquals(jsonString, json); }
@Test public void serializationSubscriptionTest() throws JsonProcessingException, MalformedURLException { ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); SubjectEntity subjectEntity = new SubjectEntity(); subjectEntity.setId(Optional.of("Bcn_Welt")); subjectEntity.setType(Optional.of("Room")); Condition condition = new Condition(); condition.setAttributes(Collections.singletonList("temperature")); condition.setExpression("q", "temperature>40"); SubjectSubscription subjectSubscription = new SubjectSubscription(Collections.singletonList(subjectEntity), condition); List<String> attributes = new ArrayList<>(); attributes.add("temperature"); attributes.add("humidity"); Notification notification = new Notification(attributes, new URL("http://localhost:1234")); notification.setThrottling(Optional.of(new Long(5))); notification.setTimesSent(12); notification.setLastNotification(Instant.parse("2015-10-05T16:00:00.10Z")); notification.setHeader("X-MyHeader", "foo"); notification.setQuery("authToken", "bar"); notification.setAttrsFormat(Optional.of(Notification.Format.keyValues)); String json = writer.writeValueAsString(new Subscription("abcdefg", subjectSubscription, notification, Instant.parse("2016-04-05T14:00:00.20Z"), Subscription.Status.active)); assertEquals(jsonString, json); }
/** @return The JSON pretty-printed representation of this configuration. */ @Override public final String toString() { final ObjectMapper mapper = new ObjectMapper() .configure(SerializationFeature.INDENT_OUTPUT, true); final DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter( "\t", DefaultIndenter.SYS_LF ); final DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); printer.withObjectIndenter(indenter); printer.withArrayIndenter(indenter); try { return mapper.writer(printer).writeValueAsString(this); } catch(final JsonProcessingException e) { throw new AssertionError(e); } }
public Response getQueryResult(final Query query) { StreamingOutput stream = new StreamingOutput() { @Override public void write( OutputStream os ) throws IOException, WebApplicationException { JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8); jg.setPrettyPrinter(new DefaultPrettyPrinter()); jg.writeStartObject(); if (query != null && query.toCypher().length() > 0) { writeQueryDetails(jg, query); System.out.println(query.toCypher()); executeQuery(jg, query); } else { jg.writeStringField("error", "No query supplied."); } jg.writeEndObject(); jg.flush(); jg.close(); } }; return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build(); }
@Test public void serializationSimpleQueryContext() throws IOException { QueryContext queryContext = createQueryContextTemperature(); ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); String json = writer.writeValueAsString(queryContext); List<EntityId> entityIdList = JsonPath.read(json, "$.entities[*]"); assertEquals(1, entityIdList.size()); assertEquals("S*", JsonPath.read(json, "$.entities[0].id")); assertEquals("TempSensor", JsonPath.read(json, "$.entities[0].type")); assertEquals(true, JsonPath.read(json, "$.entities[0].isPattern")); List<String> attributeList = JsonPath.read(json, "$.attributes[*]"); assertEquals(1, attributeList.size()); assertEquals("temp", JsonPath.read(json, "$.attributes[0]")); }
@Test public void serializationSimpleRegisterContext() throws URISyntaxException, JsonProcessingException { RegisterContext registerContext = createRegisterContextTemperature(); ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); String json = writer.writeValueAsString(registerContext); List<ContextRegistration> contextRegistrationList = JsonPath.read(json, "$.contextRegistrations[*]"); assertEquals(1, contextRegistrationList.size()); List<EntityId> entityIdList = JsonPath.read(json, "$.contextRegistrations[0].entities[*]"); assertEquals(1, entityIdList.size()); assertEquals("Room*", JsonPath.read(json, "$.contextRegistrations[0].entities[0].id")); assertEquals("Room", JsonPath.read(json, "$.contextRegistrations[0].entities[0].type")); assertEquals(true, JsonPath.read(json, "$.contextRegistrations[0].entities[0].isPattern")); List<ContextRegistrationAttribute> attributes = JsonPath.read(json, "$.contextRegistrations[0].attributes[*]"); assertEquals(1, attributes.size()); assertEquals("temperature", JsonPath.read(json, "$.contextRegistrations[0].attributes[0].name")); assertEquals("float", JsonPath.read(json, "$.contextRegistrations[0].attributes[0].type")); assertEquals(false, JsonPath.read(json, "$.contextRegistrations[0].attributes[0].isDomain")); assertEquals("http://localhost:1028/accumulate", JsonPath.read(json, "$.contextRegistrations[0].providingApplication")); assertEquals("PT10S", JsonPath.read(json, "$.duration")); }
public static String buildDefaultRestApiJson() { ObjectMapper m = ObjectMapperFactory.getObjectMapper(); ObjectNode node = m.createObjectNode(); ObjectNode n = node.putObject("rest-api"); n.put("name", "%%NAME%%"); n.put("group", "%%GROUP%%"); n.put("database", "%%DATABASE%%"); n.put("modules-database", "%%MODULES_DATABASE%%"); n.put("port", "%%PORT%%"); n.put("xdbc-enabled", true); // n.put("forests-per-host", 3); n.put("error-format", "json"); try { String json = m.writer(new DefaultPrettyPrinter()).writeValueAsString(node); json = json.replace("\"%%PORT%%\"", "%%PORT%%"); return json; } catch (JsonProcessingException ex) { throw new RuntimeException(ex); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType(MediaType.APPLICATION_JSON); resp.setCharacterEncoding(StandardCharsets.UTF_8.name()); PrintWriter printWriter = resp.getWriter(); List<AssetFilter> filters = new ArrayList<>(); filters.add(new AssetFilter("state", Arrays.asList(new Condition[] { new Condition(Operation.EQUALS, "published") }))); int assetCount = serviceLayer.countAllAssets(filters, null); JsonGenerator frontPageJsonGenerator = new JsonFactory().createGenerator(printWriter); frontPageJsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); frontPageJsonGenerator.writeStartObject(); frontPageJsonGenerator.writeStringField("serverName", "LARS"); frontPageJsonGenerator.writeNumberField("assetCount", assetCount); frontPageJsonGenerator.writeEndObject(); frontPageJsonGenerator.flush(); frontPageJsonGenerator.close(); }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(500); response.setContentType(MediaType.APPLICATION_JSON); PrintWriter printWriter = response.getWriter(); JsonGenerator frontPageJsonGenerator = new JsonFactory().createGenerator(printWriter); frontPageJsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); frontPageJsonGenerator.writeStartObject(); frontPageJsonGenerator.writeStringField("message", "Internal server error, please contact the server administrator"); frontPageJsonGenerator.writeNumberField("statusCode", response.getStatus()); frontPageJsonGenerator.writeEndObject(); frontPageJsonGenerator.flush(); frontPageJsonGenerator.close(); }
@Override public void outputScore(Score score) { Path tmpFile = null; try { if (tmpDir.isPresent()) { tmpFile = Files.createTempFile(tmpDir.get(), "score-", ".json", PosixFilePermissions.asFileAttribute(defaultPerms)); } else { tmpFile = Files.createTempFile("score-", ".json", PosixFilePermissions.asFileAttribute(defaultPerms)); } BufferedWriter writer = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8); Serialization.getJsonMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, score); Files.move(tmpFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOG.error("Error writing score to file!", e); } finally { try { if (tmpFile != null) Files.deleteIfExists(tmpFile); } catch (IOException ignored) { } } }
@Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.replaceAll(c -> { if (c instanceof MappingJackson2HttpMessageConverter) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper) { protected void writePrefix(JsonGenerator generator, Object object) throws IOException { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); if (attributes != null && attributes instanceof ServletRequestAttributes) { String attribute = ((ServletRequestAttributes) attributes).getRequest().getParameter("pretty"); if (attribute != null) { generator.setPrettyPrinter(new DefaultPrettyPrinter()); } } super.writePrefix(generator, object); } }; return converter; } else { return c; } }); }
private void refill(Model model, JobDefinition jobDefinition) { try { model.addAttribute("json", mapper.writer(new DefaultPrettyPrinter()).writeValueAsString(jobDefinition)); BaseValue value = new BaseValue(); value.setName(jobDefinition.getName()); value.setSources(jobDefinition.getSources()); value.setFilters(jobDefinition.getFilters()); model.addAttribute("baseValue", mapper.writeValueAsString(value)); model.addAttribute("storesValue", mapper.writeValueAsString(jobDefinition.getStores())); model.addAttribute("frontierValue", mapper.writeValueAsString(jobDefinition.getFrontier())); model.addAttribute("extractionValue", mapper.writeValueAsString(jobDefinition.getExtractors())); model.addAttribute("politenessValue", mapper.writeValueAsString(jobDefinition.getPoliteness())); model.addAttribute("advancedValue", mapper.writeValueAsString(jobDefinition.getClient())); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } }
public static String toString(Object o, boolean pretty) { if (o == null) { return null; } else { StringWriter sw = new StringWriter(); try { if (pretty) { jackson.writer(new DefaultPrettyPrinter()).writeValue(sw, o); } else { jackson.writeValue(sw, o); } return sw.toString(); } catch (IOException e) { //XXX signalize exception ? return o.toString(); } } }
@Inject private void load() { if(assetManager == null) { throw new RuntimeException("AssetManaget has not been set in your setup! Mapping service cannot be performed!"); } defaultTypeFactory = TypeFactory.defaultInstance(); jsonMapper.setVisibilityChecker(jsonMapper.getDeserializationConfig().getDefaultVisibilityChecker() .withCreatorVisibility(JsonAutoDetect.Visibility.NONE) .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE)); jsonMapper.configure(SerializationFeature.INDENT_OUTPUT, true).configure(Feature.ALLOW_COMMENTS, true); defaultPrettyPrinter = new DefaultPrettyPrinter(); defaultPrettyPrinter.indentArraysWith(new Lf2SpacesIndenter()); }
private static ObjectMapper prettyMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setBase64Variant(Base64Variants.MODIFIED_FOR_URL); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.registerModule(tuuidModule()); if (!Env.dev()) { mapper.registerModule(new AfterburnerModule()); } DefaultPrettyPrinter pp = new DefaultPrettyPrinter(); pp = pp.withObjectIndenter(new DefaultIndenter(" ", "\n")); mapper.setDefaultPrettyPrinter(pp); return mapper; }
private static String generateJson(Object o, boolean prettyPrint, boolean escapeNonASCII) { try { StringWriter sw = new StringWriter(); JsonGenerator jgen = new JsonFactory(mapper()).createGenerator(sw); if (prettyPrint) { jgen.setPrettyPrinter(new DefaultPrettyPrinter()); } if (escapeNonASCII) { jgen.enable(Feature.ESCAPE_NON_ASCII); } mapper().writeValue(jgen, o); sw.flush(); return sw.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
@NotNull public static Response buildStreamingResponse(@NotNull final JsonFactory factory, @NotNull final Response.Status status, @NotNull final StreamingJsonResponse jsonResponse) { return Response.status(status).entity(new StreamingOutput() { @Override public void write(final OutputStream output) throws IOException, WebApplicationException { try (JsonGenerator json = factory.createGenerator(output)) { json.setPrettyPrinter(new DefaultPrettyPrinter()); json.writeStartObject(); jsonResponse.write(json); json.writeEndObject(); } } }).type("application/json").build(); }
public void backup(OutputStream os) throws InterruptedException, IOException, KeeperException { JsonGenerator jgen = null; ZooKeeper zk = null; try { zk = options.createZooKeeper(LOGGER); jgen = JSON_FACTORY.createGenerator(os); if (options.prettyPrint) { jgen.setPrettyPrinter(new DefaultPrettyPrinter()); } jgen.writeStartObject(); if (zk.exists(options.rootPath, false) == null) { LOGGER.warn("Root path not found: {}", options.rootPath); } else { doBackup(zk, jgen, options.rootPath); } jgen.writeEndObject(); } finally { if (jgen != null) { jgen.close(); } if (zk != null) { zk.close(); } } }
public void testCustomRootSeparatorWithPP() throws Exception { JsonFactory f = new JsonFactory(); // first, no pretty-printing (will still separate root values with a space!) assertEquals("{} {} []", _generateRoot(f, null)); // First with default pretty printer, default configs: assertEquals("{ } { } [ ]", _generateRoot(f, new DefaultPrettyPrinter())); // then custom: assertEquals("{ }|{ }|[ ]", _generateRoot(f, new DefaultPrettyPrinter("|"))); }
public void testPrettyPrinter() throws Exception { PrettyPrinter p = new DefaultPrettyPrinter(); byte[] stuff = jdkSerialize(p); PrettyPrinter back = jdkDeserialize(stuff); // what should we test? assertNotNull(back); }
/** * Static factory that creates {@link com.fasterxml.jackson.databind.ObjectWriter}s. * * @return utility that will allow client to serialize wrapper contents as json */ public static ObjectWriter getObjectWriter(boolean filterMeta) { DefaultIndenter withLinefeed = new DefaultIndenter(" ", "\n"); DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); printer.indentObjectsWith(withLinefeed); ObjectMapper om = new ObjectMapper(); if (filterMeta) { outfitMetadataFilter(om); } return om.writer().with(printer); }
private void json(Record record) throws IOException { JsonWriter writer = new JsonWriter(); JsonNode written = writer.writeRecord(record); String output = new ObjectMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(written); System.out.println(output); Object got = new JsonReader().readRecord(record.getSchema(), written); Assert.assertEquals(record, got); }
private void enableDisableJSONGeneratorFeature(JsonGenerator jg) { jg.enable(Feature.ESCAPE_NON_ASCII); jg.disable(Feature.AUTO_CLOSE_TARGET); jg.setPrettyPrinter(new DefaultPrettyPrinter()); if (PDXTOJJSON_UNQUOTEFIELDNAMES) jg.disable(Feature.QUOTE_FIELD_NAMES); }
public JSonDatabaseWriter(final OutputStream outStream) throws IOException { this.mOutStream = outStream; JsonFactory f = new JsonFactory(); mGen = f.createGenerator(outStream, JsonEncoding.UTF8); mGen.setPrettyPrinter(new DefaultPrettyPrinter()); }
private JsonGenerator createJsonGenerator(StringWriter out) throws SchemaException{ try { JsonFactory factory = new JsonFactory(); JsonGenerator generator = factory.createGenerator(out); generator.setPrettyPrinter(new DefaultPrettyPrinter()); generator.setCodec(configureMapperForSerialization()); return generator; } catch (IOException ex){ throw new SchemaException("Schema error during serializing to JSON.", ex); } }
public YAMLGenerator createJacksonGenerator(StringWriter out) throws SchemaException{ try { MidpointYAMLFactory factory = new MidpointYAMLFactory(); MidpointYAMLGenerator generator = (MidpointYAMLGenerator) factory.createGenerator(out); generator.setPrettyPrinter(new DefaultPrettyPrinter()); generator.setCodec(configureMapperForSerialization()); return generator; } catch (IOException ex){ throw new SchemaException("Schema error during serializing to JSON.", ex); } }
public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.constructType(DefaultPrettyPrinter.class); objectMapper.writerWithDefaultPrettyPrinter(); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; }
@Bean public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.constructType(DefaultPrettyPrinter.class); objectMapper.writerWithDefaultPrettyPrinter(); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; }
@Bean public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.constructType(DefaultPrettyPrinter.class); objectMapper.writerWithDefaultPrettyPrinter(); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; }
public void serialize(Scene scene, Writer writer) throws IOException { _jsonGenerator = JSON_FACTORY.createGenerator(writer); _jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); _jsonGenerator.writeStartObject(); _jsonGenerator.writeStringField(SceneSerializationConstant.SCENE_TAG_NAME, scene.getName()); writeHttpExchanges(scene.getRecordedHttpExchangeList()); _jsonGenerator.writeEndObject(); _jsonGenerator.close(); }
@Test public void serializationSimpleRegisterContextResponse() throws IOException { RegisterContextResponse registerContextResponse = new RegisterContextResponse("52a744b011f5816465943d58"); registerContextResponse.setDuration("P1M"); ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); String json = writer.writeValueAsString(registerContextResponse); assertEquals("52a744b011f5816465943d58", JsonPath.read(json, "$.registrationId")); assertEquals("P1M", JsonPath.read(json, "$.duration")); }