本文整理匯總了Java中org.codehaus.jackson.JsonGenerator.useDefaultPrettyPrinter方法的典型用法代碼示例。如果您正苦於以下問題:Java JsonGenerator.useDefaultPrettyPrinter方法的具體用法?Java JsonGenerator.useDefaultPrettyPrinter怎麽用?Java JsonGenerator.useDefaultPrettyPrinter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.codehaus.jackson.JsonGenerator
的用法示例。
在下文中一共展示了JsonGenerator.useDefaultPrettyPrinter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeInternal
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
JsonGenerator jsonGenerator =
this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
// A workaround for JsonGenerators not applying serialization features
// https://github.com/FasterXML/jackson-databind/issues/12
if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
jsonGenerator.useDefaultPrettyPrinter();
}
try {
if (this.jsonPrefix != null) {
jsonGenerator.writeRaw(this.jsonPrefix);
}
this.objectMapper.writeValue(jsonGenerator, object);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
示例2: write
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
private void write(DataOutput out) throws IOException {
// This is just a JSON experiment
System.out.println("Dumping the StatePool's in JSON format.");
ObjectMapper outMapper = new ObjectMapper();
outMapper.configure(
SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
// define a module
SimpleModule module = new SimpleModule("State Serializer",
new Version(0, 1, 1, "FINAL"));
// add the state serializer
//module.addSerializer(State.class, new StateSerializer());
// register the module with the object-mapper
outMapper.registerModule(module);
JsonFactory outFactory = outMapper.getJsonFactory();
JsonGenerator jGen =
outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8);
jGen.useDefaultPrettyPrinter();
jGen.writeObject(this);
jGen.close();
}
示例3: createJsonGenerator
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
private JsonGenerator createJsonGenerator(Configuration conf, Path path)
throws IOException {
FileSystem outFS = path.getFileSystem(conf);
CompressionCodec codec =
new CompressionCodecFactory(conf).getCodec(path);
OutputStream output;
Compressor compressor = null;
if (codec != null) {
compressor = CodecPool.getCompressor(codec);
output = codec.createOutputStream(outFS.create(path), compressor);
} else {
output = outFS.create(path);
}
JsonGenerator outGen = outFactory.createJsonGenerator(output,
JsonEncoding.UTF8);
outGen.useDefaultPrettyPrinter();
return outGen;
}
示例4: main
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
public static void main(String[] args) throws IOException {
final Configuration conf = new Configuration();
final FileSystem lfs = FileSystem.getLocal(conf);
for (String arg : args) {
Path filePath = new Path(arg).makeQualified(lfs);
String fileName = filePath.getName();
if (fileName.startsWith("input")) {
LoggedDiscreteCDF newResult = histogramFileToCDF(filePath, lfs);
String testName = fileName.substring("input".length());
Path goldFilePath = new Path(filePath.getParent(), "gold"+testName);
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
FSDataOutputStream ostream = lfs.create(goldFilePath, true);
JsonGenerator gen = factory.createJsonGenerator(ostream,
JsonEncoding.UTF8);
gen.useDefaultPrettyPrinter();
gen.writeObject(newResult);
gen.close();
} else {
System.err.println("Input file not started with \"input\". File "+fileName+" skipped.");
}
}
}
示例5: writeToResponse
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
/**
* Writes the response values back to the http response. This allows the calling code to
* parse the response values for display to the user.
*
* @param responseMap the response params to write to the http response
* @param response the http response
* @throws IOException
*/
private static void writeToResponse(Map<String, String> responseMap, HttpServletResponse response) throws IOException {
// Note: setting the content-type to text/html because otherwise IE prompt the user to download
// the result rather than handing it off to the GWT form response handler.
// See JIRA issue https://issues.jboss.org/browse/SRAMPUI-103
response.setContentType("text/html; charset=UTF8"); //$NON-NLS-1$
JsonFactory f = new JsonFactory();
JsonGenerator g = f.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
g.useDefaultPrettyPrinter();
g.writeStartObject();
for (java.util.Map.Entry<String, String> entry : responseMap.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
g.writeStringField(key, val);
}
g.writeEndObject();
g.flush();
g.close();
}
示例6: toString
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
public String toString(boolean pretty) {
try {
StringWriter writer = new StringWriter();
JsonGenerator gen = FACTORY.createJsonGenerator(writer);
if (pretty)
gen.useDefaultPrettyPrinter();
if (this instanceof PrimitiveSchema || this instanceof UnionSchema) {
gen.writeStartObject();
gen.writeFieldName("type");
}
writeJSON(gen, new SchemaNames());
if (this instanceof PrimitiveSchema || this instanceof UnionSchema) {
gen.writeEndObject();
}
gen.flush();
return writer.toString();
} catch (IOException e) {
throw new BaijiRuntimeException(e);
}
}
示例7: toString
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
/**
* Render this as <a href="http://json.org/">JSON</a>.
*
* @param pretty if true, pretty-print JSON.
*/
public String toString(boolean pretty) {
try {
StringWriter writer = new StringWriter();
JsonGenerator gen = FACTORY.createJsonGenerator(writer);
if (pretty) gen.useDefaultPrettyPrinter();
if (this instanceof PrimitiveSchema || this instanceof UnionSchema) {
gen.writeStartObject();
gen.writeFieldName("type");
}
writeJson(gen, new SchemaNames(), null);
if (this instanceof PrimitiveSchema || this instanceof UnionSchema) {
gen.writeEndObject();
}
gen.flush();
return writer.toString();
} catch (IOException e) {
throw new BaijiRuntimeException(e);
}
}
示例8: open
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
public Writer open(final PrintWriter writer) throws IOException {
final JsonGenerator jg = jsonFactory.createJsonGenerator(writer);
jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
jg.useDefaultPrettyPrinter();
jg.writeStartObject();
return new Writer() {
@Override
public void flush() throws IOException {
jg.flush();
}
@Override
public void close() throws IOException {
jg.close();
}
@Override
public void write(String key, String value) throws JsonGenerationException, IOException {
jg.writeStringField(key, value);
}
@Override
public int write(MBeanServer mBeanServer, ObjectName qry, String attribute,
boolean description)
throws IOException {
return JSONBean.write(jg, mBeanServer, qry, attribute, description);
}
};
}
示例9: writeInternal
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
protected void writeInternal(Object object,HttpServletResponse response) throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = this.getJsonEncoding(mediaType);
JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), encoding);
if(this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
jsonGenerator.useDefaultPrettyPrinter();
}
try {
this.objectMapper.writeValue(jsonGenerator, object);
} catch (JsonProcessingException var6) {
throw new HttpMessageNotWritableException("Could not write JSON: " + var6.getMessage(), var6);
}
}
示例10: writeValueWithConf
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
private void writeValueWithConf(JsonGenerator jgen, Object value,
JsonSerialize.Inclusion inc) throws IOException,
JsonGenerationException, JsonMappingException {
SerializationConfig cfg = copySerializationConfig();
cfg = cfg.withSerializationInclusion(inc);
// [JACKSON-96]: allow enabling pretty printing for ObjectMapper
// directly
if (cfg.isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
jgen.useDefaultPrettyPrinter();
}
// [JACKSON-282]: consider Closeable
if (cfg.isEnabled(SerializationConfig.Feature.CLOSE_CLOSEABLE)
&& (value instanceof Closeable)) {
configAndWriteCloseable(jgen, value, cfg);
return;
}
boolean closed = false;
try {
_serializerProvider.serializeValue(cfg, jgen, value,
_serializerFactory);
closed = true;
jgen.close();
} finally {
/*
* won't try to close twice; also, must catch exception (so it
* will not mask exception that is pending)
*/
if (!closed) {
try {
jgen.close();
} catch (IOException ioe) {
}
}
}
}
示例11: close
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
public void close() {
// close the json file and write filters
JsonGenerator generator;
try {
generator = jFactory.createJsonGenerator(new FileWriter(jsonFile));
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
generator.setCodec(mapper);
generator.useDefaultPrettyPrinter();
generator.writeTree(rootNode);
generator.close();
//now generate the dot file
File extractDir = new File(docDir, extract);
File xPathDotFile = new File(extractDir, "xpath.dot");
xPathDotWriter = new DotWriter();
xPathDotWriter.open(xPathDotFile);
xPathDotWriter.setOdfFilename(srcsArray.get(0).get("source").getTextValue());
xPathDotWriter.setIncludeLegend(false);
xPathDotWriter.writePaths(xPathRoot);
xPathDotWriter.close();
} catch (IOException e) {
LOGGER.severe(jsonFile.getName() + " IO Error");
e.printStackTrace();
}
}
示例12: updateGenerator
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
/**
* Update the generator with a default codec and pretty printer
*
* @param jsonFactory Factory to set as codec
* @param jsonGenerator Generator to configure
*/
private static void updateGenerator(JsonFactory jsonFactory, JsonGenerator jsonGenerator) {
ObjectMapper mapper = new ObjectMapper(jsonFactory);
//Update the annotation interceptor to also include jaxb annotations as a second choice
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector() {
/**
* BUG FIX:
* By contract, if findSerializationInclusion didn't encounter any annotations that should change the
* inclusion value, it should return the default value it has received; but actually returns null, which
* overrides the NON_NULL option we set.
* The doc states issue JACKSON-256 which was supposed to be fixed in 1.5.0. *twilight zone theme song*
*/
@Override
public JsonSerialize.Inclusion findSerializationInclusion(Annotated a, JsonSerialize.Inclusion defValue) {
JsonSerialize.Inclusion inclusion = super.findSerializationInclusion(a, defValue);
if (inclusion == null) {
return defValue;
}
return inclusion;
}
};
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);
mapper.getSerializationConfig().setAnnotationIntrospector(pair);
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
jsonGenerator.setCodec(mapper);
jsonGenerator.useDefaultPrettyPrinter();
}
示例13: toJson
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
public static String toJson(Object object, boolean prettyPrint) {
StringWriter stringWriter = new StringWriter();
try {
JsonGenerator jg = jsonFactory.createJsonGenerator(stringWriter);
if (prettyPrint) {
jg.useDefaultPrettyPrinter();
}
objectMapper.writeValue(jg, object);
} catch (IOException e) {
e.printStackTrace();
}
return stringWriter.toString();
}
示例14: displayFile
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
@Override
public void displayFile(FileSystem fs, Path path, OutputStream outputStream,
int startLine, int endLine) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Display Parquet file: " + path.toUri().getPath());
}
JsonGenerator json = null;
AvroParquetReader<GenericRecord> parquetReader = null;
try {
parquetReader = new AvroParquetReader<GenericRecord>(path);
// Initialize JsonGenerator.
json = new JsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);
json.useDefaultPrettyPrinter();
// Declare the avroWriter encoder that will be used to output the records
// as JSON but don't construct them yet because we need the first record
// in order to get the Schema.
DatumWriter<GenericRecord> avroWriter = null;
Encoder encoder = null;
long endTime = System.currentTimeMillis() + STOP_TIME;
int line = 1;
while (line <= endLine && System.currentTimeMillis() <= endTime) {
GenericRecord record = parquetReader.read();
if (record == null) {
break;
}
if (avroWriter == null) {
Schema schema = record.getSchema();
avroWriter = new GenericDatumWriter<GenericRecord>(schema);
encoder = EncoderFactory.get().jsonEncoder(schema, json);
}
if (line >= startLine) {
String recordStr = "\n\nRecord " + line + ":\n";
outputStream.write(recordStr.getBytes("UTF-8"));
avroWriter.write(record, encoder);
encoder.flush();
}
++line;
}
}
catch (IOException e) {
outputStream.write(("Error in displaying Parquet file: " +
e.getLocalizedMessage()).getBytes("UTF-8"));
throw e;
}
catch (Throwable t) {
logger.error(t.getMessage());
return;
}
finally {
if (json != null) {
json.close();
}
parquetReader.close();
}
}
示例15: displayFile
import org.codehaus.jackson.JsonGenerator; //導入方法依賴的package包/類
@Override
public void displayFile(FileSystem fs,
Path path,
OutputStream outputStream,
int startLine,
int endLine) throws IOException {
if (logger.isDebugEnabled())
logger.debug("display avro file:" + path.toUri().getPath());
DataFileStream<Object> avroDatastream = null;
JsonGenerator g = null;
try {
avroDatastream = getAvroDataStream(fs, path);
Schema schema = avroDatastream.getSchema();
DatumWriter<Object> avroWriter = new GenericDatumWriter<Object>(schema);
g = new JsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);
g.useDefaultPrettyPrinter();
Encoder encoder = EncoderFactory.get().jsonEncoder(schema, g);
long endTime = System.currentTimeMillis() + STOP_TIME;
int lineno = 1; // line number starts from 1
while (avroDatastream.hasNext() && lineno <= endLine && System.currentTimeMillis() <= endTime) {
Object datum = avroDatastream.next();
if (lineno >= startLine) {
String record = "\n\n Record " + lineno + ":\n";
outputStream.write(record.getBytes("UTF-8"));
avroWriter.write(datum, encoder);
encoder.flush();
}
lineno++;
}
} catch (IOException e) {
outputStream.write(("Error in display avro file: " + e.getLocalizedMessage()).getBytes("UTF-8"));
throw e;
} finally {
if (g != null) {
g.close();
}
avroDatastream.close();
}
}