当前位置: 首页>>代码示例>>Java>>正文


Java JsonGenerator.useDefaultPrettyPrinter方法代码示例

本文整理汇总了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);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:MappingJacksonHttpMessageConverter.java

示例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();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:24,代码来源:StatePool.java

示例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;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:Anonymizer.java

示例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.");
    }
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:28,代码来源:TestHistograms.java

示例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();
}
 
开发者ID:Teiid-Designer,项目名称:teiid-webui,代码行数:27,代码来源:DataVirtUploadServlet.java

示例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);
    }
}
 
开发者ID:adohe,项目名称:Bottlenose,代码行数:25,代码来源:Schema.java

示例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);
    }
}
 
开发者ID:archcentric,项目名称:BaijiSerializer4J,代码行数:29,代码来源:Schema.java

示例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);
    }
  };
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:30,代码来源:JSONBean.java

示例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);
    }
}
 
开发者ID:autumnkuang,项目名称:nenlvse1.0,代码行数:14,代码来源:CustomMappingJacksonJsonpView.java

示例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) {
			}
		}
	}
}
 
开发者ID:neoremind,项目名称:fountain,代码行数:38,代码来源:JsonUtils.java

示例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();
	}
}
 
开发者ID:hammyau,项目名称:ODFExplorer,代码行数:28,代码来源:FilteredXPathGraph.java

示例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();
}
 
开发者ID:alancnet,项目名称:artifactory,代码行数:38,代码来源:JacksonFactory.java

示例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();
}
 
开发者ID:krisjin,项目名称:bscl,代码行数:14,代码来源:JsonHelper.java

示例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();
	}
}
 
开发者ID:JasonBian,项目名称:azkaban,代码行数:62,代码来源:ParquetFileViewer.java

示例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();
	}
}
 
开发者ID:JasonBian,项目名称:azkaban,代码行数:45,代码来源:AvroFileViewer.java


注:本文中的org.codehaus.jackson.JsonGenerator.useDefaultPrettyPrinter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。