类com.fasterxml.jackson.core.util.DefaultPrettyPrinter源码实例Demo

下面列出了怎么用com.fasterxml.jackson.core.util.DefaultPrettyPrinter的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: teku   文件: JsonProvider.java
private void addTekuMappers() {
  SimpleModule module = new SimpleModule("TekuJson", new Version(1, 0, 0, null, null, null));

  module.addSerializer(Bitlist.class, new BitlistSerializer());
  module.addDeserializer(Bitlist.class, new BitlistDeserializer());
  module.addDeserializer(Bitvector.class, new BitvectorDeserializer());
  module.addSerializer(Bitvector.class, new BitvectorSerializer());

  module.addSerializer(BLSPubKey.class, new BLSPubKeySerializer());
  module.addDeserializer(BLSPubKey.class, new BLSPubKeyDeserializer());
  module.addDeserializer(BLSSignature.class, new BLSSignatureDeserializer());
  module.addSerializer(BLSSignature.class, new BLSSignatureSerializer());

  module.addDeserializer(Bytes32.class, new Bytes32Deserializer());
  module.addDeserializer(Bytes4.class, new Bytes4Deserializer());
  module.addSerializer(Bytes4.class, new Bytes4Serializer());
  module.addDeserializer(Bytes.class, new BytesDeserializer());
  module.addSerializer(Bytes.class, new BytesSerializer());

  module.addDeserializer(UnsignedLong.class, new UnsignedLongDeserializer());
  module.addSerializer(UnsignedLong.class, new UnsignedLongSerializer());

  objectMapper.registerModule(module).writer(new DefaultPrettyPrinter());
}
 
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);
    }
}
 
源代码3 项目: crnk-framework   文件: OASGenerator.java
@VisibleForTesting
static String generateOpenApiContent(OpenAPI openApi, OutputFormat outputFormat, Boolean sort) {
  if (sort) {
    ObjectMapper objectMapper = outputFormat.mapper();
    objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    try {
      return objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(openApi);
    } catch (JsonProcessingException e) {
      LOGGER.error("Sorting failed!");
      return outputFormat.pretty(openApi);
    }
  } else {
    return outputFormat.pretty(openApi);
  }
}
 
源代码4 项目: json-snapshot.github.io   文件: SnapshotMatcher.java
private static PrettyPrinter buildDefaultPrettyPrinter() {
  DefaultPrettyPrinter pp =
      new DefaultPrettyPrinter("") {
        @Override
        public DefaultPrettyPrinter withSeparators(Separators separators) {
          this._separators = separators;
          this._objectFieldValueSeparatorWithSpaces =
              separators.getObjectFieldValueSeparator() + " ";
          return this;
        }
      };
  Indenter lfOnlyIndenter = new DefaultIndenter("  ", "\n");
  pp.indentArraysWith(lfOnlyIndenter);
  pp.indentObjectsWith(lfOnlyIndenter);
  return pp;
}
 
源代码5 项目: carnotzet   文件: JsonMerger.java
/**
 * Properties of file2 have precedence over the ones in file1
 */
@Override
public void merge(Path file1Path, Path file2Path, Path output) {
	ObjectMapper mapper = new ObjectMapper();
	ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
	try (InputStream in1 = Files.newInputStream(file1Path)) {
		try (InputStream in2 = Files.newInputStream(file2Path)) {
			JsonNode file1 = mapper.readTree(in1);
			JsonNode file2 = mapper.readTree(in2);
			JsonNode merged = merge(file1, file2);
			writer.writeValue(output.toFile(), merged);
		}
	}
	catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
源代码6 项目: vethrfolnir-mu   文件: DataMappingService.java
@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());
}
 
源代码7 项目: rapidoid   文件: JSON.java
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;
}
 
源代码8 项目: cassandra-mesos-deprecated   文件: JaxRsUtils.java
@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();
}
 
源代码9 项目: tutorials   文件: JacksonSerializeUnitTest.java
@Test
public void whenCustomSerialize_thenCorrect() throws ParseException, IOException {

    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

    final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
    final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));

    final SimpleModule module = new SimpleModule();
    module.addSerializer(new ActorJacksonSerializer(ActorJackson.class));
    final ObjectMapper mapper = new ObjectMapper();

    final String jsonResult = mapper.registerModule(module)
        .writer(new DefaultPrettyPrinter())
        .writeValueAsString(movieWithNullValue);

    final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class);
    final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
        .writeValueAsString(json);

    Assert.assertEquals(jsonResult, expectedOutput);
}
 
源代码10 项目: swagger-maven-plugin   文件: JaxrsReaderTest.java
@Test
public void createCommonParameters() throws Exception {
    reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class));
    Swagger result = reader.read(CommonParametersApi.class);
    Parameter headerParam = result.getParameter("headerParam");
    assertTrue(headerParam instanceof HeaderParameter);
    Parameter queryParam = result.getParameter("queryParam");
    assertTrue(queryParam instanceof QueryParameter);

    result = reader.read(ReferenceCommonParametersApi.class);
    Operation get = result.getPath("/apath").getGet();
    List<Parameter> parameters = get.getParameters();
    for (Parameter parameter : parameters) {
        assertTrue(parameter instanceof RefParameter);
    }

    ObjectMapper mapper = Json.mapper();
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    String json = jsonWriter.writeValueAsString(result);
    JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json"));
    JsonAssert.assertJsonEquals(expectJson, json);
}
 
源代码11 项目: zoocreeper   文件: Backup.java
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();
        }
    }
}
 
protected AbstractJackson2HttpMessageConverter(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	setDefaultCharset(DEFAULT_CHARSET);
	DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
	prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	this.ssePrettyPrinter = prettyPrinter;
}
 
protected void init(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	setDefaultCharset(DEFAULT_CHARSET);
	DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
	prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	this.ssePrettyPrinter = prettyPrinter;
}
 
源代码14 项目: dbsync   文件: JSonDatabaseWriter.java
public JSonDatabaseWriter(final OutputStream outStream) throws IOException {
    this.mOutStream = outStream;

    JsonFactory f = new JsonFactory();
    mGen = f.createGenerator(outStream, JsonEncoding.UTF8);
    mGen.setPrettyPrinter(new DefaultPrettyPrinter());
}
 
源代码15 项目: rdf4j   文件: AbstractSPARQLJSONWriter.java
@Override
public void startDocument() throws QueryResultHandlerException {
	if (!documentOpen) {
		documentOpen = true;
		headerOpen = false;
		headerComplete = false;
		tupleVariablesFound = false;
		firstTupleWritten = false;
		linksFound = false;

		if (getWriterConfig().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);
		}

		try {
			if (getWriterConfig().isSet(BasicQueryWriterSettings.JSONP_CALLBACK)) {
				// SES-1019 : Write the callbackfunction name as a wrapper for
				// the results here
				String callbackName = getWriterConfig().get(BasicQueryWriterSettings.JSONP_CALLBACK);
				jg.writeRaw(callbackName);
				jg.writeRaw("(");
			}
			jg.writeStartObject();
		} catch (IOException e) {
			throw new QueryResultHandlerException(e);
		}
	}
}
 
源代码16 项目: rdf4j   文件: RDFJSONWriter.java
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();
}
 
源代码17 项目: burp-rest-api   文件: UserConfigUtils.java
/**
 * Given a userconfig, copy it in a new temporary file and injects all the registered extensions
 * @param path a userconfig path to be injected
 * @return a new userconfig path
 * @throws IOException when one of the two userconfig is not accessible/writable/creatable
 */
public String injectExtensions(String path) throws IOException {
    Path userOptionsTempFile = Files.createTempFile("user-options_", ".json");
    FileCopyUtils.copy(new File(path), userOptionsTempFile.toFile());

    //addBurpExtensions here to the temporary file and return the handle to the new temporary file
    //- read all file in in jackson object
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    JsonNode tree = objectMapper.readTree(userOptionsTempFile.toFile());
    //- inject the burp extensions here inside the user configuration
    JsonNode user_options = safeGet(objectMapper, tree, "user_options");
    JsonNode extender = safeGet(objectMapper, user_options, "extender");
    JsonNode extension = extender.get("extensions");
    if (!extension.isArray()) {
        ArrayNode array = objectMapper.createArrayNode();
        ((ObjectNode)extender).replace("extensions", array);
        extension = array;
    }
    for (Extension e : extensions) {
        ((ArrayNode) extension).addPOJO(e);
    }
    //- write the jackson configuration inside the temporary user configuration
    objectMapper.writer(new DefaultPrettyPrinter()).writeValue(userOptionsTempFile.toFile(), tree);

    userOptionsTempFile.toFile().deleteOnExit();
    return userOptionsTempFile.toAbsolutePath().toString();
}
 
源代码18 项目: flashback   文件: SceneSerializer.java
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();
}
 
源代码19 项目: bonita-ui-designer   文件: JacksonObjectMapper.java
public byte[] toPrettyJson(Object object, Class<?> serializationView) throws IOException {
    // Use UTF8 to accept any character and have platform-independent files.
    return objectMapper.writerWithView(serializationView)
            .with(new DefaultPrettyPrinter()
                .withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE))
            .writeValueAsString(object)
            .getBytes(StandardCharsets.UTF_8);
}
 
源代码20 项目: formatter-maven-plugin   文件: JsonFormatter.java
@Override
public void init(Map<String, String> options, ConfigurationSource cfg) {
    super.initCfg(cfg);

    int indent = Integer.parseInt(options.getOrDefault("indent", "4"));
    String lineEnding = options.getOrDefault("lineending", System.lineSeparator());
    boolean spaceBeforeSeparator = Boolean.parseBoolean(options.getOrDefault("spaceBeforeSeparator", "true"));

    formatter = new ObjectMapper();

    // Setup a pretty printer with an indenter (indenter has 4 spaces in this case)
    DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(Strings.repeat(" ", indent), lineEnding);
    DefaultPrettyPrinter printer = new DefaultPrettyPrinter() {
        private static final long serialVersionUID = 1L;

        @Override
        public DefaultPrettyPrinter createInstance() {
            return new DefaultPrettyPrinter(this);
        }

        @Override
        public DefaultPrettyPrinter withSeparators(Separators separators) {
            this._separators = separators;
            this._objectFieldValueSeparatorWithSpaces = (spaceBeforeSeparator ? " " : "")
                    + separators.getObjectFieldValueSeparator() + " ";
            return this;
        }
    };

    printer.indentObjectsWith(indenter);
    printer.indentArraysWith(indenter);
    formatter.setDefaultPrettyPrinter(printer);
    formatter.enable(SerializationFeature.INDENT_OUTPUT);
}
 
源代码21 项目: webanno   文件: JSONUtil.java
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();
}
 
源代码22 项目: depgraph-maven-plugin   文件: JsonGraphFormatter.java
private String serialize(JsonGraph jsonGraph) {
  DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter()
      .withObjectIndenter(new DefaultIndenter("  ", "\n"));

  ObjectWriter writer = this.objectMapper.writer(prettyPrinter);
  StringWriter jsonWriter = new StringWriter();
  try {
    writer.writeValue(jsonWriter, jsonGraph);
  } catch (IOException e) {
    // should never happen with StringWriter
    throw new IllegalStateException(e);
  }

  return jsonWriter.toString();
}
 
源代码23 项目: status   文件: TestDependencyReport.java
@Test
public void testJsonInvariants() throws Exception {
    final Dependency alwaysDies = new PingableDependency("alwaysDies", "", BuiltIns.REQUIRED) {
        public void ping () throws Exception {
            // throw a new checked exception caused by an unchecked exceptions
            throw new IOException(new NullPointerException());
        }

        @Override
        public String getDocumentationUrl() {
            return null;
        }
    };
    final DependencyManager manager = new DependencyManager();
    manager.addDependency(alwaysDies);

    final CheckResultSet results = manager.evaluate();
    final StringWriter out = new StringWriter();
    new JsonFactory(new ObjectMapper()).createJsonGenerator(out).setPrettyPrinter(new DefaultPrettyPrinter()).writeObject(results.summarize(true));
    final String json = out.toString();

    final List<String> expectedJsonFingerprints = ImmutableList.of(
                    "\"status\" : \"OUTAGE\"",
                    "\"exception\" : \"IOException\"",
                    "\"exception\" : \"NullPointerException\"");
    for (final String fingerprint:  expectedJsonFingerprints) {
        Assert.assertTrue(
                "Expected to find fingerprint '" + fingerprint + "' in json: " + json,
                json.contains(fingerprint));
    }
}
 
protected void writeAvroSchemaToFile( String schemaFilename ) throws KettleFileException, IOException {
  ObjectNode schemaObjectNode = this.getSchemaObjectNode();
  if ( schemaObjectNode != null && schemaFilename != null ) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer( new DefaultPrettyPrinter() );
    writer.writeValue( KettleVFS.getOutputStream( schemaFilename, variableSpace, false ), schemaObjectNode );
  }
}
 
源代码25 项目: jackson-jr   文件: JSON.java
@Override
public PrettyPrinter getPrettyPrinter() {
    PrettyPrinter pp = _prettyPrinter;
    if (pp != null) {
        if (pp instanceof Instantiatable<?>) {
            pp = (PrettyPrinter) ((Instantiatable<?>) pp).createInstance();
        }
        return pp;
    }
    if (isEnabled(Feature.PRETTY_PRINT_OUTPUT)) {
        return new DefaultPrettyPrinter();
    }
    return null;
}
 
源代码26 项目: buck   文件: AbstractQueryCommand.java
private static <T extends SortedMap<String, Object>> void printAttributesAsJson(
    ImmutableSortedMap<String, T> result, PrintStream printStream) throws IOException {
  ObjectMappers.WRITER
      .with(
          new DefaultPrettyPrinter().withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE))
      // Jackson closes stream by default - we do not want it
      .without(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
      .writeValue(printStream, result);

  // Jackson does not append a newline after final closing bracket. Do it to make JSON look
  // nice on console.
  printStream.println();
}
 
源代码27 项目: usergrid   文件: ExportServiceImpl.java
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;
}
 
源代码28 项目: usergrid   文件: ExportingToolBase.java
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;
}
 
protected AbstractJackson2HttpMessageConverter(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
	prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	this.ssePrettyPrinter = prettyPrinter;
}
 
源代码30 项目: spring-analysis-note   文件: Jackson2JsonEncoder.java
private static PrettyPrinter initSsePrettyPrinter() {
	DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
	printer.indentObjectsWith(new DefaultIndenter("  ", "\ndata:"));
	return printer;
}
 
 同包方法