Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#setPrettyPrinter()
The following examples show how to use
com.fasterxml.jackson.core.JsonGenerator#setPrettyPrinter() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PluginDescriptor.java From glowroot with Apache License 2.0 | 6 votes |
public static String writeValue(List<PluginDescriptor> pluginDescriptors) throws IOException { ObjectMapper mapper = ObjectMappers.create(); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter()); jg.writeStartArray(); for (PluginDescriptor pluginDescriptor : pluginDescriptors) { ObjectNode objectNode = mapper.valueToTree(pluginDescriptor); ObjectMappers.stripEmptyContainerNodes(objectNode); jg.writeTree(objectNode); } jg.writeEndArray(); } finally { jg.close(); } // newline is not required, just a personal preference sb.append(ObjectMappers.NEWLINE); return sb.toString(); }
Example 2
Source File: AdminJsonService.java From glowroot with Apache License 2.0 | 6 votes |
@GET(path = "/backend/admin/json", permission = "admin:view") String getAllAdmin() throws Exception { Object config; if (central) { config = configRepository.getAllCentralAdminConfig(); } else { config = configRepository.getAllEmbeddedAdminConfig(); } ObjectNode rootNode = mapper.valueToTree(config); AllAdminConfigUtil.removePasswords(rootNode); ObjectMappers.stripEmptyContainerNodes(rootNode); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter()); jg.writeObject(rootNode); } finally { jg.close(); } // newline is not required, just a personal preference sb.append(ObjectMappers.NEWLINE); return sb.toString(); }
Example 3
Source File: ConfigJsonService.java From glowroot with Apache License 2.0 | 6 votes |
@GET(path = "/backend/config/json", permission = "agent:config:view") String getAllConfig(@BindAgentId String agentId) throws Exception { AgentConfig config = configRepository.getAllConfig(agentId); ObjectNode configRootNode = mapper.valueToTree(AllConfigDto.create(config)); ObjectMappers.stripEmptyContainerNodes(configRootNode); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter()); jg.writeObject(configRootNode); } finally { jg.close(); } // newline is not required, just a personal preference sb.append(ObjectMappers.NEWLINE); return sb.toString(); }
Example 4
Source File: Backup.java From zoocreeper with Apache License 2.0 | 6 votes |
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(); } } }
Example 5
Source File: RDFJSONWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void modelToRdfJsonInternal(final Model graph, final WriterConfig writerConfig, final JsonGenerator jg) throws IOException, JsonGenerationException { if (writerConfig.get(BasicWriterSettings.PRETTY_PRINT)) { // SES-2011: Always use \n for consistency Indenter indenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE; // By default Jackson does not pretty print, so enable this unless // PRETTY_PRINT setting is disabled DefaultPrettyPrinter pp = new DefaultPrettyPrinter().withArrayIndenter(indenter) .withObjectIndenter(indenter); jg.setPrettyPrinter(pp); } jg.writeStartObject(); for (final Resource nextSubject : graph.subjects()) { jg.writeObjectFieldStart(RDFJSONWriter.resourceToString(nextSubject)); for (final IRI nextPredicate : graph.filter(nextSubject, null, null).predicates()) { jg.writeArrayFieldStart(nextPredicate.stringValue()); for (final Value nextObject : graph.filter(nextSubject, nextPredicate, null).objects()) { // contexts are optional, so this may return empty in some // scenarios depending on the interpretation of the way contexts // work final Set<Resource> contexts = graph.filter(nextSubject, nextPredicate, nextObject).contexts(); RDFJSONWriter.writeObject(nextObject, contexts, jg); } jg.writeEndArray(); } jg.writeEndObject(); } jg.writeEndObject(); }
Example 6
Source File: JSONUtil.java From webanno with Apache License 2.0 | 5 votes |
public static String toJsonString(ObjectMapper aMapper, boolean aPretty, Object aObject) throws IOException { StringWriter out = new StringWriter(); JsonGenerator jsonGenerator = aMapper.getFactory().createGenerator(out); if (aPretty) { jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter() .withObjectIndenter(new DefaultIndenter().withLinefeed("\n"))); } jsonGenerator.writeObject(aObject); return out.toString(); }
Example 7
Source File: ConfigFileUtil.java From glowroot with Apache License 2.0 | 5 votes |
private static String writeConfigAsString(ObjectNode rootObjectNode, List<String> keyOrder) throws IOException { ObjectNode orderedRootObjectNode = getOrderedObjectNode(rootObjectNode, keyOrder); ObjectMappers.stripEmptyContainerNodes(orderedRootObjectNode); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.setPrettyPrinter(ObjectMappers.getPrettyPrinter()); jg.writeTree(orderedRootObjectNode); } finally { jg.close(); } // newline is not required, just a personal preference return sb.toString() + ObjectMappers.NEWLINE; }
Example 8
Source File: JacksonUtils.java From ameba with MIT License | 5 votes |
/** * <p>configureGenerator.</p> * * @param uriInfo a {@link javax.ws.rs.core.UriInfo} object. * @param generator a {@link com.fasterxml.jackson.core.JsonGenerator} object. * @param isDev a boolean. */ public static void configureGenerator(UriInfo uriInfo, JsonGenerator generator, boolean isDev) { MultivaluedMap<String, String> params = uriInfo.getQueryParameters(); String pretty = params.getFirst("pretty"); if ("false".equalsIgnoreCase(pretty)) { generator.setPrettyPrinter(null); } else if (pretty != null && !"false".equalsIgnoreCase(pretty) || isDev) { generator.useDefaultPrettyPrinter(); } String unicode = params.getFirst("unicode"); if (unicode != null && !"false".equalsIgnoreCase(unicode)) { generator.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII); } }
Example 9
Source File: ExportServiceImpl.java From usergrid with Apache License 2.0 | 5 votes |
protected JsonGenerator getJsonGenerator( File ephermal ) throws IOException { //TODO:shouldn't the below be UTF-16? JsonGenerator jg = jsonFactory.createJsonGenerator( ephermal, JsonEncoding.UTF8 ); jg.setPrettyPrinter( new DefaultPrettyPrinter( ) ); jg.setCodec( new ObjectMapper() ); return jg; }
Example 10
Source File: ExportingToolBase.java From usergrid with Apache License 2.0 | 5 votes |
protected JsonGenerator getJsonGenerator( File outFile ) throws IOException { PrintWriter out = new PrintWriter( outFile, "UTF-8" ); JsonGenerator jg = jsonFactory.createJsonGenerator( out ); jg.setPrettyPrinter( new DefaultPrettyPrinter() ); jg.setCodec( new ObjectMapper() ); return jg; }
Example 11
Source File: JsonRecordWriter.java From Bats with Apache License 2.0 | 4 votes |
@Override public void init(Map<String, String> writerOptions) throws IOException { this.location = writerOptions.get("location"); this.prefix = writerOptions.get("prefix"); this.fieldDelimiter = writerOptions.get("separator"); this.extension = writerOptions.get("extension"); this.useExtendedOutput = Boolean.parseBoolean(writerOptions.get("extended")); this.skipNullFields = Boolean.parseBoolean(writerOptions.get("skipnulls")); final boolean uglify = Boolean.parseBoolean(writerOptions.get("uglify")); this.fs = FileSystem.get(fsConf); Path fileName = new Path(location, prefix + "_" + index + "." + extension); try { // json writer does not support partitions, so only one file can be created // and thus only one location should be deleted in case of abort // to ensure that our writer was the first to create output file, // we create empty output file first and fail if file exists cleanUpLocation = storageStrategy.createFileAndApply(fs, fileName); // since empty output file will be overwritten (some file systems may restrict append option) // we need to re-apply file permission stream = fs.create(fileName); storageStrategy.applyToFile(fs, fileName); JsonGenerator generator = factory.createGenerator(stream).useDefaultPrettyPrinter() .configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, !Boolean.parseBoolean(writerOptions.get("enableNanInf"))); if (uglify) { generator = generator.setPrettyPrinter(new MinimalPrettyPrinter(LINE_FEED)); } if(useExtendedOutput){ gen = new ExtendedJsonOutput(generator); }else{ gen = new BasicJsonOutput(generator); } logger.debug("Created file: {}", fileName); } catch (IOException ex) { logger.error("Unable to create file: " + fileName, ex); throw ex; } }
Example 12
Source File: JSONUtil.java From dremio-oss with Apache License 2.0 | 4 votes |
@Override public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException { JsonGenerator generator = super.createGenerator(out, enc); generator.setPrettyPrinter(pp); return generator; }
Example 13
Source File: JacksonStreamingWriteExample.java From journaldev with MIT License | 4 votes |
public static void main(String[] args) throws IOException { Employee emp = JacksonObjectMapperExample.createEmployee(); JsonGenerator jsonGenerator = new JsonFactory() .createGenerator(new FileOutputStream("stream_emp.txt")); //for pretty printing jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); jsonGenerator.writeStartObject(); // start root object jsonGenerator.writeNumberField("id", emp.getId()); jsonGenerator.writeStringField("name", emp.getName()); jsonGenerator.writeBooleanField("permanent", emp.isPermanent()); jsonGenerator.writeObjectFieldStart("address"); //start address object jsonGenerator.writeStringField("street", emp.getAddress().getStreet()); jsonGenerator.writeStringField("city", emp.getAddress().getCity()); jsonGenerator.writeNumberField("zipcode", emp.getAddress().getZipcode()); jsonGenerator.writeEndObject(); //end address object jsonGenerator.writeArrayFieldStart("phoneNumbers"); for(long num : emp.getPhoneNumbers()) jsonGenerator.writeNumber(num); jsonGenerator.writeEndArray(); jsonGenerator.writeStringField("role", emp.getRole()); jsonGenerator.writeArrayFieldStart("cities"); //start cities array for(String city : emp.getCities()) jsonGenerator.writeString(city); jsonGenerator.writeEndArray(); //closing cities array jsonGenerator.writeObjectFieldStart("properties"); Set<String> keySet = emp.getProperties().keySet(); for(String key : keySet){ String value = emp.getProperties().get(key); jsonGenerator.writeStringField(key, value); } jsonGenerator.writeEndObject(); //closing properties jsonGenerator.writeEndObject(); //closing root object jsonGenerator.flush(); jsonGenerator.close(); }
Example 14
Source File: JsonUtils.java From sql-layer with GNU Affero General Public License v3.0 | 4 votes |
public static void makePretty(JsonGenerator generator) { generator.setPrettyPrinter(prettyPrinter); }
Example 15
Source File: JSonDatabaseWriter.java From dbsync with Apache License 2.0 | 2 votes |
long write(File file) throws IOException { long timestamp = System.currentTimeMillis(); if (file.exists()) { file.delete(); } JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(file, JsonEncoding.UTF8); g.setPrettyPrinter(new DefaultPrettyPrinter() ); g.writeStartObject(); g.writeFieldName("database"); g.writeStartObject(); // Nome database g.writeStringField("name",databaseName); // Tabelle g.writeFieldName("tables"); g.writeStartArray(); for (Map.Entry<String, Integer> entry : tablesToWrite.entrySet()) { g.writeStartObject(); g.writeStringField("name",entry.getKey()); g.writeArrayFieldStart("records"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); for (int i = 0; i < entry.getValue();++i) { g.writeStartObject(); g.writeNumberField("cId", new Date().getTime()); String name = entry.getKey(); name = name + " " + i; g.writeStringField("name", name); g.writeStringField("dateCreated", simpleDateFormat.format(new Date())); g.writeStringField("dateUpdated", simpleDateFormat.format(new Date())); g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); g.writeEndObject(); g.close(); return System.currentTimeMillis() - timestamp; }