當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。