下面列出了怎么用com.fasterxml.jackson.core.util.DefaultPrettyPrinter的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
@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);
}
}
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;
}
/**
* 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);
}
}
@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;
}
@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();
}
@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);
}
@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);
}
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;
}
public JSonDatabaseWriter(final OutputStream outStream) throws IOException {
this.mOutStream = outStream;
JsonFactory f = new JsonFactory();
mGen = f.createGenerator(outStream, JsonEncoding.UTF8);
mGen.setPrettyPrinter(new DefaultPrettyPrinter());
}
@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);
}
}
}
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();
}
/**
* 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();
}
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();
}
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);
}
@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);
}
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();
}
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();
}
@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 );
}
}
@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;
}
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();
}
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;
}
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;
}
private static PrettyPrinter initSsePrettyPrinter() {
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(new DefaultIndenter(" ", "\ndata:"));
return printer;
}