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


Java JsonGenerator类代码示例

本文整理汇总了Java中org.codehaus.jackson.JsonGenerator的典型用法代码示例。如果您正苦于以下问题:Java JsonGenerator类的具体用法?Java JsonGenerator怎么用?Java JsonGenerator使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


JsonGenerator类属于org.codehaus.jackson包,在下文中一共展示了JsonGenerator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: AvroFileInputStream

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
public AvroFileInputStream(FileStatus status) throws IOException {
  pos = 0;
  buffer = new byte[0];
  GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
  FileContext fc = FileContext.getFileContext(new Configuration());
  fileReader =
    DataFileReader.openReader(new AvroFSInput(fc, status.getPath()),reader);
  Schema schema = fileReader.getSchema();
  writer = new GenericDatumWriter<Object>(schema);
  output = new ByteArrayOutputStream();
  JsonGenerator generator =
    new JsonFactory().createJsonGenerator(output, JsonEncoding.UTF8);
  MinimalPrettyPrinter prettyPrinter = new MinimalPrettyPrinter();
  prettyPrinter.setRootValueSeparator(System.getProperty("line.separator"));
  generator.setPrettyPrinter(prettyPrinter);
  encoder = EncoderFactory.get().jsonEncoder(schema, generator);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:18,代码来源:Display.java

示例2: 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

示例3: configureFeature

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
private void configureFeature(Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		this.objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		this.objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationConfig.Feature) {
		this.objectMapper.configure((SerializationConfig.Feature) feature, enabled);
	}
	else if (feature instanceof DeserializationConfig.Feature) {
		this.objectMapper.configure((DeserializationConfig.Feature) feature, enabled);
	}
	else {
		throw new IllegalArgumentException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:JacksonObjectMapperFactoryBean.java

示例4: 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

示例5: 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

示例6: 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

示例7: next

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
@Override
public String next()
{
    CSVRecord record = inner.next();
    StringWriter json = new StringWriter();
    try {
        JsonGenerator gen = jsonFactory.createJsonGenerator(json);
        gen.writeStartObject();
        for (CSVHeaderMap.Entry entry : headerMap.entries()) {
            String name = entry.getName();
            String value = record.get(entry.getIndex());

            gen.writeFieldName(name);
            entry.getWriter().write(gen, value);
        }
        gen.writeEndObject();
        gen.close();
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
    return json.toString();
}
 
开发者ID:CyberAgent,项目名称:embulk-input-parquet_hadoop,代码行数:24,代码来源:CSVAsJSONIterator.java

示例8: writeAttribute

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
private static void writeAttribute(JsonGenerator jg, String attName, final String descriptionStr,
    Object value)
throws IOException {
  boolean description = false;
  if (descriptionStr != null && descriptionStr.length() > 0 && !attName.equals(descriptionStr)) {
    description = true;
    jg.writeFieldName(attName);
    jg.writeStartObject();
    jg.writeFieldName("description");
    jg.writeString(descriptionStr);
    jg.writeFieldName("value");
    writeObject(jg, description, value);
    jg.writeEndObject();
  } else {
    jg.writeFieldName(attName);
    writeObject(jg, description, value);
  }
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:19,代码来源:JSONBean.java

示例9: setBeforeInfo

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
/**
 * Populate transaction meta data into the record if requested.
 *
 * @param jg the handle to the JsonGenerator
 * @param op the database operation we are processing.
 * @throws IOException if a JSON encoding error occurs
 */
private void setBeforeInfo(JsonGenerator jg, DownstreamOperation op) throws IOException {
    LOG.debug("setBeforeInfo()");

    jg.writeFieldName("priorValues");
    jg.writeStartObject();
    // loop through operatons with calls to appropriate jg.write() methods
    for (DownstreamColumnData col : op.getBefores()) {
        if (textOnly == true) {
            jg.writeStringField(col.getBDName(), col.asString());
        } else {
            // Encode the data appropriately: handle numbers as numbers, etc.
            int jdbcType;
            jdbcType = op.getTableMeta().getColumn(col.getOrigName()).getJdbcType();
            encodeColumn(col, jdbcType, jg);
        }
    }
    jg.writeEndObject();
}
 
开发者ID:oracle,项目名称:bdglue,代码行数:26,代码来源:JsonEncoder.java

示例10: writeJsonFields

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
/**
 * Writes the records schema in JSON format
 *
 * @param writer   JSON writer
 * @param names    list of named schemas already written
 * @param encSpace enclosing namespace of the record schema
 */
@Override
protected void writeJsonFields(JsonGenerator writer, SchemaNames names, String encSpace)
        throws IOException {
    super.writeJsonFields(writer, names, encSpace);

    // we allow reading for empty fields, so writing of records with empty fields are allowed as well
    if (_request) {
        writer.writeFieldName("request");
    } else {
        writer.writeFieldName("fields");
    }
    writer.writeStartArray();

    if (_fields != null && !_fields.isEmpty()) {
        for (Field field : this) {
            field.writeJson(writer, names, getNamespace()); // use the namespace of the record for the fields
        }
    }
    writer.writeEndArray();
}
 
开发者ID:archcentric,项目名称:BaijiSerializer4J,代码行数:28,代码来源:RecordSchema.java

示例11: JsonStreamCodec

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
public JsonStreamCodec(Map<Class<?>, Class<? extends StringCodec<?>>> codecs)
{
  JacksonObjectMapperProvider jomp = new JacksonObjectMapperProvider();
  if (codecs != null) {
    for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry: codecs.entrySet()) {
      try {
        @SuppressWarnings("unchecked")
        final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance();
        jomp.addSerializer(new SerializerBase(entry.getKey())
        {
          @Override
          public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException
          {
            jgen.writeString(codec.toString(value));
          }

        });
      } catch (Exception ex) {
        logger.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex);
      }
    }
  }
  mapper = jomp.getContext(null);
}
 
开发者ID:apache,项目名称:apex-core,代码行数:25,代码来源:JsonStreamCodec.java

示例12: serialize

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
@Override
public void serialize(Map<String, Object> fields, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	jgen.writeStartObject();
	for (Entry<String, Object> entry : fields.entrySet()) {
		Object objectValue = entry.getValue();
		if (objectValue instanceof Date) {
			Date date = (Date) objectValue;
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
			simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland"));
			String formattedDate = simpleDateFormat.format(date);
			jgen.writeObjectField(entry.getKey().toString(), formattedDate);
		} else {
			jgen.writeObjectField(entry.getKey().toString(), objectValue);
		}
	}
	jgen.writeEndObject();
}
 
开发者ID:cheetah100,项目名称:gravity,代码行数:20,代码来源:MapJsonSerializer.java

示例13: write

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
/**
 * Used to write the state of the SessionManager instance to disk, when we
 * are persisting the state of the ClusterManager
 * @param jsonGenerator The JsonGenerator instance being used to write JSON
 *                      to disk
 * @throws IOException
 */
public void write(JsonGenerator jsonGenerator) throws IOException {
  jsonGenerator.writeStartObject();
  // retiredSessions and numRetiredSessions need not be persisted

  // sessionCounter can be set to 0, when the SessionManager is instantiated

  // sessions begins
  jsonGenerator.writeFieldName("sessions");
  jsonGenerator.writeStartObject();
  for (String sessionId : sessions.keySet()) {
    jsonGenerator.writeFieldName(sessionId);
    sessions.get(sessionId).write(jsonGenerator);
  }
  jsonGenerator.writeEndObject();
  // sessions ends

  jsonGenerator.writeNumberField("sessionCounter",
                                  sessionCounter.longValue());

  jsonGenerator.writeEndObject();

  // We can rebuild runnableSessions
  // No need to write startTime and numRetiredSessions
}
 
开发者ID:rhli,项目名称:hadoop-EAR,代码行数:32,代码来源:SessionManager.java

示例14: 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

示例15: serialize

import org.codehaus.jackson.JsonGenerator; //导入依赖的package包/类
/**
  * Performs the serialization of a OneComponentTime object
  */
@Override
public void serialize(CumulativeTimeBucket ctb,
                JsonGenerator jGen,
                SerializerProvider serializer) 
                throws IOException, JsonProcessingException {
    jGen.writeStartObject();
    Timestamp ts = new Timestamp(ctb.getStartTimeNs()/1000000);
    jGen.writeStringField("start-time", ts.toString());
    jGen.writeStringField("current-time", 
      new Timestamp(System.currentTimeMillis()).toString());
    jGen.writeNumberField("total-packets", ctb.getTotalPktCnt());
    jGen.writeNumberField("average", ctb.getAverageProcTimeNs());
    jGen.writeNumberField("min", ctb.getMinTotalProcTimeNs());
    jGen.writeNumberField("max", ctb.getMaxTotalProcTimeNs());
    jGen.writeNumberField("std-dev", ctb.getTotalSigmaProcTimeNs());
    jGen.writeArrayFieldStart("modules");
    for (OneComponentTime oct : ctb.getModules()) {
        serializer.defaultSerializeValue(oct, jGen);
    }
    jGen.writeEndArray();
    jGen.writeEndObject();
}
 
开发者ID:vishalshubham,项目名称:Multipath-Hedera-system-in-Floodlight-controller,代码行数:26,代码来源:CumulativeTimeBucketJSONSerializer.java


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