Java com.fasterxml.jackson.core.util.DefaultPrettyPrinter 代码实例

・11 分钟阅读

以下是展示如何使用com.fasterxml.jackson.core.util.DefaultPrettyPrinter的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


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;
}
 

实例 2


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

实例 3


public String toJson() {
    try {
        return Jackson.OBJECT_MAPPER.writer(new DefaultPrettyPrinter()).writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Error serializing config to json", e);
    }
}
 

实例 4


@Override
public void appendHtml(final Writer writer) throws IOException {
  writer.append("<h2>Uri Information</h2>n")
      .append("<ul class="json">n<li>n");
  JsonGenerator json = new JsonFactory().createGenerator(writer)
      .setPrettyPrinter(new DefaultPrettyPrinter());
  appendJson(json);
  json.close();
  writer.append("n</li>n</ul>n");
}
 

实例 5


@SuppressWarnings({"unchecked", "unused"})
public void toJson(final OutputStream out, final boolean pretty) throws IOException
{
    final String parentPath = getParentPath() == null ? "" : getParentPath();
    final JsonGenerator generator = new JsonFactory().createJsonGenerator(out);
    generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (pretty) {
        generator.setPrettyPrinter(new DefaultPrettyPrinter());
    }
    generator.writeStartObject();
    generator.writeObjectField(JSON_LISTING_PATH, getPath());
    generator.writeObjectField(JSON_LISTING_PARENT_PATH, parentPath);
    generator.writeArrayFieldStart(JSON_LISTING_ENTRIES);
    // Important: need to flush before appending pre-serialized events
    generator.flush();
    for (HdfsEntry entry : getEntries()) {
        entry.toJson(generator);
    }
    generator.writeEndArray();
    generator.writeEndObject();
    generator.close();
}
 

实例 6


@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"));
}
 

实例 7


protected JsonGenerator getJsonGenerator(Set<URI> flags, Writer writer) throws IOException {
    JsonGenerator g = getJsonFactory(flags).createJsonGenerator(writer);
    if (flags.contains(RepresentationFactory.PRETTY_PRINT)) {
        g.setPrettyPrinter(new DefaultPrettyPrinter());
    }
    return g;
}
 

实例 8


public JSONPrettyPrint() {
    ObjectMapper mapper = new ObjectMapper();
    Indenter indenter = new PrettyIndenter();
    DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
    prettyPrinter.indentObjectsWith(indenter);
    prettyPrinter.indentArraysWith(indenter);
    writer = mapper.writer().with(prettyPrinter);
}
 

实例 9


protected void prettyPrint(Object o) {
    try {
        System.out.println(mapper().writer(new DefaultPrettyPrinter()).writeValueAsString(o));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 

实例 10


@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));
    }
}
 

实例 11


@Deprecated
@Override
protected RisonGenerator _createJsonGenerator(Writer out, IOContext ctxt) throws IOException {
    RisonGenerator gen = new RisonGenerator(ctxt, _generatorFeatures, _risonGeneratorFeatures, _objectCodec, out);
    SerializableString rootSep = _rootValueSeparator;
    if (rootSep != DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR) {
        gen.setRootValueSeparator(rootSep);
    }
    return gen;
}
 

实例 12


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);
}
 

实例 13


public <T> void write(T bean, Writer writer) {
  try {
    JsonGenerator jgen = new JsonFactory().createGenerator(writer);
    if (pretty) {
      jgen.setPrettyPrinter(new DefaultPrettyPrinter());
    }
    JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(mappings,jgen);
    jsonStreamWriter.writeObject(bean);
    jgen.flush();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 

实例 14


@Override
public JsonGenerator useDefaultPrettyPrinter() {
    /* 28-Sep-2012, tatu: As per [Issue#84], should not override a
     *  pretty printer if one already assigned.
     */
    if (getPrettyPrinter() != null) {
        return this;
    }
    return setPrettyPrinter(new DefaultPrettyPrinter());
}
 

实例 15


public void testPrettyPrinter() throws Exception
{
    PrettyPrinter p = new DefaultPrettyPrinter();
    byte[] stuff = jdkSerialize(p);
    PrettyPrinter back = jdkDeserialize(stuff);
    // what should we test?
    assertNotNull(back);
}
 
讨论
淘淘あ西西 profile image