Java Code Examples for com.fasterxml.jackson.core.JsonGenerator

The following are top voted examples for showing how to use com.fasterxml.jackson.core.JsonGenerator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: beaker-notebook-archive   File: CategoryLinesSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(CategoryLines categoryLines,
                      JsonGenerator jgen,
                      SerializerProvider provider) throws
                                                   IOException,
                                                   JsonProcessingException {
  jgen.writeStartObject();

  super.serialize(categoryLines, jgen, provider);

  if (categoryLines.getWidth() != null) {
    jgen.writeObjectField("width", categoryLines.getWidth());
  }
  if (categoryLines.getStyles() != null) {
    jgen.writeObjectField("styles", categoryLines.getStyles());
  } else {
    jgen.writeObjectField("style", categoryLines.getStyle().toString());
  }
  if (categoryLines.getInterpolation() != null) {
    jgen.writeObjectField("interpolation", categoryLines.getInterpolation());
  }

  jgen.writeEndObject();
}
 
Example 2
Project: OperatieBRP   File: ObjectSerializer.java   View source code 6 votes vote down vote up
private void writeHistorieRecordKop(final JsonGenerator jgen, final BlobViewGroep groep) throws IOException {
    jgen.writeArrayFieldStart("kolomtitels");
    jgen.writeString(INDEX_OBJECT);
    if (isFormeel(groep.getElement())) {
        jgen.writeString(TIJDSTIP_REGISTRATIE);
        jgen.writeString(TIJDSTIP_VERVAL);
        jgen.writeString(NADERE_AANDUIDING_VERVAL);
        jgen.writeString(ActieType.INHOUD.getOmschrijving());
        jgen.writeString(ActieType.VERVAL.getOmschrijving());
        jgen.writeString(CSS);

    } else if (isMaterieel(groep.getElement())) {
        jgen.writeString(DATUM_INGANG_GELDIGHEID);
        jgen.writeString(DATUM_EINDE_GELDIGHEID);
        jgen.writeString(TIJDSTIP_REGISTRATIE);
        jgen.writeString(TIJDSTIP_VERVAL);
        jgen.writeString(NADERE_AANDUIDING_VERVAL);
        jgen.writeString(ActieType.INHOUD.getOmschrijving());
        jgen.writeString(ActieType.AANPASSING.getOmschrijving());
        jgen.writeString(ActieType.VERVAL.getOmschrijving());
        jgen.writeString(CSS);
    }
    jgen.writeString(DETAIL);
    jgen.writeEndArray();
}
 
Example 3
Project: beaker-notebook-archive   File: ChartSerializer.java   View source code 6 votes vote down vote up
protected void serialize(T chart, JsonGenerator jgen) throws IOException {

    super.serialize(chart, jgen);

    String type = chart.getClass().getSimpleName();
    if ("SimpleTimePlot".equals(type)){
      jgen.writeObjectField("type", "TimePlot");
    }else {
      jgen.writeObjectField("type", type);
    }

    jgen.writeObjectField(INIT_WIDTH, chart.getInitWidth());
    jgen.writeObjectField(INIT_HEIGHT, chart.getInitHeight());
    jgen.writeObjectField(CHART_TITLE, chart.getTitle());
    jgen.writeObjectField(SHOW_LEGEND, chart.getShowLegend());
    jgen.writeObjectField(USE_TOOL_TIP, chart.getUseToolTip());
    jgen.writeObjectField(LEGEND_POSITION, chart.getLegendPosition());
    jgen.writeObjectField("legend_layout", chart.getLegendLayout());
    jgen.writeObjectField("custom_styles", chart.getCustomStyles());
    jgen.writeObjectField("element_styles", chart.getElementStyles());
  }
 
Example 4
Project: teamcity-hashicorp-vault-plugin   File: Jackson2ObjectMapperBuilder.java   View source code 6 votes vote down vote up
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example 5
Project: oneops   File: MetricsElasticsearchModule.java   View source code 6 votes vote down vote up
@Override
public void serialize(JsonMeter jsonMeter,
                      JsonGenerator json,
                      SerializerProvider provider) throws IOException {
    json.writeStartObject();
    json.writeStringField("name", jsonMeter.name());
    json.writeObjectField(timestampFieldname, jsonMeter.timestampAsDate());
    Meter meter = jsonMeter.value();
    json.writeNumberField("count", meter.getCount());
    json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor);
    json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor);
    json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor);
    json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor);
    json.writeStringField("units", rateUnit);
    addOneOpsMetadata(json);
    json.writeEndObject();
}
 
Example 6
Project: iextrading4j   File: TradingStatusTypeSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(final TradingStatusType value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
    if (value == null || value == TradingStatusType.UNKNOWN) {
        gen.writeNull();
        return;
    }

    switch (value) {
        case TRADING_HALTED:
            gen.writeString("H");
            break;
        case TRADING_HALT_RELEASED_INTO_ORDER_ACCEPTANCE_PERIOD:
            gen.writeString("O");
            break;
        case TRADING_PAUSED_AND_ORDER_ACCEPTANCE_PERIOD_ON_IEX:
            gen.writeString("P");
            break;
        case TRADING_ON_IEX:
            gen.writeString("T");
            break;
        default:
            gen.writeNull();
            break;
    }
}
 
Example 7
Project: GitHub   File: GeneratorFailFromReaderTest.java   View source code 6 votes vote down vote up
private void _testFailOnWritingStringFromReaderWithTooFewCharacters(JsonFactory f, boolean useReader) throws Exception{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        String testStr = "aaaaaaaaa";
        StringReader reader = new StringReader(testStr);
        gen.writeFieldName("a");
        gen.writeString(reader, testStr.length() + 1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() ': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "Didn't read enough from reader");
    }
    gen.close();
}
 
Example 8
Project: wamp2spring   File: WelcomeMessage.java   View source code 6 votes vote down vote up
@Override
public void serialize(JsonGenerator generator) throws IOException {
	generator.writeNumber(getCode());
	generator.writeNumber(this.sessionId);

	generator.writeStartObject();

	generator.writeObjectFieldStart("roles");
	for (WampRole wampRole : this.roles) {
		generator.writeObjectFieldStart(wampRole.getRole());
		if (wampRole.hasFeatures()) {
			generator.writeObjectFieldStart("features");
			for (String feature : wampRole.getFeatures()) {
				generator.writeBooleanField(feature, true);
			}
			generator.writeEndObject();
		}
		generator.writeEndObject();
	}
	generator.writeEndObject();

	if (this.realm != null) {
		generator.writeStringField("realm", this.realm);
	}
	generator.writeEndObject();
}
 
Example 9
Project: alfresco-remote-api   File: WebScriptOptionsMetaData.java   View source code 6 votes vote down vote up
@Override
public void writeMetaData(OutputStream out, ResourceWithMetadata resource, Map<String, ResourceWithMetadata> allApiResources) throws IOException
{
    
    final Object result = processResult(resource,allApiResources);

    assistant.getJsonHelper().withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {           
           objectMapper.writeValue(generator, result);
        }
    });
}
 
Example 10
Project: OperatieBRP   File: BerichtListSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(final BerichtListView value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
    jgen.writeStartObject();
    if (value.getBericht() != null) {
        JsonUtils.writeAsInteger(jgen, BerichtModule.ID, ObjectUtils.getWaarde(value, "bericht.id"));
        JsonUtils.writeAsInteger(jgen, BerichtModule.SOORT, ObjectUtils.getWaarde(value, "bericht.soortBericht.id"));
        JsonUtils.writeAsInteger(jgen, BerichtModule.ZENDENDE_PARTIJ, ObjectUtils.getWaarde(value, "bericht.zendendePartij"));
        JsonUtils.writeAsInteger(jgen, BerichtModule.ONTVANGENDE_PARTIJ, ObjectUtils.getWaarde(value, "bericht.ontvangendePartij"));
        JsonUtils.writeAsString(jgen, BerichtModule.REFERENTIENUMMER, value.getBericht().getReferentieNummer());
        JsonUtils.writeAsString(jgen, BerichtModule.CROSS_REFERENTIENUMMER, value.getBericht().getCrossReferentieNummer());
        JsonUtils.writeAsString(jgen, BerichtModule.VERZENDDATUM, ObjectUtils.getGeformateerdeWaarde(value, "bericht.datumTijdVerzending", sdf));
        JsonUtils.writeAsString(jgen, BerichtModule.ONTVANGSTDATUM, ObjectUtils.getGeformateerdeWaarde(value, "bericht.datumTijdOntvangst", sdf));
        JsonUtils.writeAsInteger(jgen, BerichtModule.SOORT_SYNCHRONISATIE, ObjectUtils.getWaarde(value, "bericht.soortSynchronisatie.id"));
        JsonUtils.writeAsInteger(jgen, BerichtModule.VERWERKINGSWIJZE, ObjectUtils.getWaarde(value, "bericht.verwerkingswijze.id"));
        JsonUtils.writeAsInteger(jgen, BerichtModule.BIJHOUDING, ObjectUtils.getWaarde(value, "bericht.bijhoudingResultaat.id"));
    }
    jgen.writeEndObject();

}
 
Example 11
Project: OperatieBRP   File: ObjectSerializer.java   View source code 6 votes vote down vote up
private void maakCssLinkObject(final ActieType actieType, final BlobViewObject actie, final StringBuilder ccsClassBuilder, final JsonGenerator jgen)
        throws IOException {
    if (actie != null) {
        final BlobViewObject administratieveHandeling = actie.getParent();

        ccsClassBuilder.append(BRP_MARKEER);
        ccsClassBuilder.append(administratieveHandeling.getObjectsleutel());
        ccsClassBuilder.append(" ");
        jgen.writeObjectFieldStart(actieType.getOmschrijving());
        jgen.writeStringField(TYPE, CSS_LINK);
        jgen.writeStringField(LINK_TEKST, "Ja (actie " + actie.getObjectsleutel() + ")");
        jgen.writeStringField(LINK, BRP_MARKEER + administratieveHandeling.getObjectsleutel());
        jgen.writeEndObject();
    } else {
        jgen.writeObjectFieldStart(actieType.getOmschrijving());
        jgen.writeStringField(TYPE, CSS_LINK);
        jgen.writeStringField(LINK_TEKST, "Nee");
        jgen.writeStringField(LINK, "");
        jgen.writeEndObject();
    }
}
 
Example 12
Project: OperatieBRP   File: VersionSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(final Version value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
    jgen.writeStartObject();

    writeVersieRegel(jgen, value.getMainVersion());

    jgen.writeArrayFieldStart(VersieModule.COMPONENTEN);
    for (final VersionLine component : value.getComponentVersions()) {
        jgen.writeStartObject();
        writeVersieRegel(jgen, component);
        jgen.writeEndObject();
    }
    jgen.writeEndArray();

    jgen.writeEndObject();
}
 
Example 13
Project: wamp2spring   File: YieldMessage.java   View source code 6 votes vote down vote up
@Override
public void serialize(JsonGenerator generator) throws IOException {
	generator.writeNumber(getCode());
	generator.writeNumber(this.requestId);
	generator.writeStartObject();
	generator.writeEndObject();

	if (this.argumentsKw != null) {
		if (this.arguments == null) {
			generator.writeStartArray();
			generator.writeEndArray();
		}
		else {
			generator.writeObject(this.arguments);
		}
		generator.writeObject(this.argumentsKw);
	}
	else if (this.arguments != null) {
		generator.writeObject(this.arguments);
	}
}
 
Example 14
Project: crnk-framework   File: LinksInformationSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(LinksInformation value, JsonGenerator gen, SerializerProvider serializers)
		throws IOException {

	gen.writeStartObject();

	BeanInformation info = BeanInformation.get(value.getClass());

	for (String attrName : info.getAttributeNames()) {
		BeanAttributeInformation attribute = info.getAttribute(attrName);
		Object linkValue = attribute.getValue(value);
		if (linkValue != null) {
			gen.writeObjectFieldStart(attrName);
			if (linkValue instanceof String) {
				gen.writeStringField(SerializerUtil.HREF, linkValue.toString());
			}
			else {
				gen.writeObject(linkValue);
			}
			gen.writeEndObject();
		}
	}

	gen.writeEndObject();

}
 
Example 15
Project: etomica   File: WrapperSerializer.java   View source code 6 votes vote down vote up
@Override
    public void serialize(Wrapper<?> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        // TODO: maybe find a cleaner way to do this
        if(Vector.class.isAssignableFrom(value.getWrappedClass())) {
            // value is a vector, just write the coordinates
            gen.writeObject(((Vector) value.getWrapped()).toArray());
            return;
        }
        gen.writeStartObject();
        gen.writeStringField("class", value.getWrappedClass().getSimpleName());
        gen.writeNumberField("id", value.getWrappedId());
        value.getValues().forEach((name, obj) -> {
            try {
                gen.writeObjectField(name, obj);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
//        for(Property p : value.getProperties()) {
//            gen.writeObjectField(p.getName(), p);
//        }
        gen.writeEndObject();
    }
 
Example 16
Project: dremio-oss   File: BasicJsonOutput.java   View source code 6 votes vote down vote up
protected BasicJsonOutput(JsonGenerator gen, DateOutputFormat dateOutput) {
  Preconditions.checkNotNull(dateOutput);
  Preconditions.checkNotNull(gen);

  this.gen = gen;

  switch (dateOutput) {
  case SQL: {
    dateFormatter = DateUtility.formatDate.withZoneUTC();
    timeFormatter = DateUtility.formatTime.withZoneUTC();
    timestampFormatter = DateUtility.formatTimeStampMilli.withZoneUTC();
    break;
  }
  case ISO: {
    dateFormatter = ISODateTimeFormat.date().withZoneUTC();
    timeFormatter = ISODateTimeFormat.time().withZoneUTC();
    timestampFormatter = ISODateTimeFormat.dateTime().withZoneUTC();
    break;
  }

  default:
    throw new UnsupportedOperationException(String.format("Unable to support date output of type %s.", dateOutput));
  }
}
 
Example 17
Project: fresco_floodlight   File: StatsReplySerializer.java   View source code 6 votes vote down vote up
public static void serializeFeaturesReply(OFFeaturesReply fr, JsonGenerator jGen) throws IOException, JsonProcessingException {
	/* Common to All OF Versions */			
	jGen.writeStringField("capabilities", fr.getCapabilities().toString());
	jGen.writeStringField("dpid", fr.getDatapathId().toString());
	jGen.writeNumberField("buffers", fr.getNBuffers());
	jGen.writeNumberField("tables", fr.getNTables());
	jGen.writeStringField("version", fr.getVersion().toString());

	if (fr.getVersion().compareTo(OFVersion.OF_13) < 0) { // OF1.3+ break this out into port_config
		serializePortDesc(fr.getPorts(), jGen);
	}
	if (fr.getVersion().compareTo(OFVersion.OF_10) == 0) {
		String actions = "[";
		for (OFActionType action : fr.getActions()) {
			actions =  actions + action.toString() + ", ";
		}
		actions = actions.substring(0, actions.length() - 2); // remove ending space+comma
		actions = actions + "]";
		jGen.writeStringField("actions", actions);
	}
}
 
Example 18
Project: beaker-notebook-archive   File: BasicObjectSerializer.java   View source code 6 votes vote down vote up
@Override
public boolean writeObject(Object obj, JsonGenerator jgen, boolean expand) throws JsonProcessingException, IOException {
  logger.debug("generic map");
  // convert this 'on the fly' to a map of objects
  Map<?,?> m = (Map<?,?>) obj;

  Set<?> kset = m.keySet();
  if (kset.size()==0 || !(kset.iterator().next() instanceof String))
    jgen.writeObject(obj.toString());
  else {
    jgen.writeStartObject();
    for (Object k : kset) {
      jgen.writeFieldName((null==k)?"null":k.toString());
      if (!parent.writeObject(m.get(k), jgen, false))
        jgen.writeObject(m.get(k)!=null ? (m.get(k).toString()) : "null");
    }
    jgen.writeEndObject();
  }
  return true;
}
 
Example 19
Project: fresco_floodlight   File: CumulativeTimeBucketJSONSerializer.java   View source code 6 votes vote down vote up
/**
  * 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();
}
 
Example 20
Project: alfresco-remote-api   File: JsonJacksonTests.java   View source code 6 votes vote down vote up
@Test
public void testSerializeComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\""));
}
 
Example 21
Project: powsybl-core   File: JsonUtil.java   View source code 5 votes vote down vote up
public static void writeJson(Writer writer, Consumer<JsonGenerator> consumer) {
    Objects.requireNonNull(writer);
    Objects.requireNonNull(consumer);
    JsonFactory factory = new JsonFactory();
    try (JsonGenerator generator = factory.createGenerator(writer)) {
        generator.useDefaultPrettyPrinter();
        consumer.accept(generator);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 22
Project: Equella   File: RestStringsModule.java   View source code 5 votes vote down vote up
@Override
public void serialize(I18NStrings value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
	JsonProcessingException
{
	jgen.writeStartObject();
	Map<String, String> strings = value.getStrings();
	for( Entry<String, String> string : strings.entrySet() )
	{
		jgen.writeFieldName(string.getKey());
		jgen.writeString(string.getValue());
	}
	jgen.writeEndObject();
}
 
Example 23
Project: fresco_floodlight   File: SwitchPortBandwidthSerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(SwitchPortBandwidth spb, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException {
	jGen.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true);

	jGen.writeStartObject();
	jGen.writeStringField("dpid", spb.getSwitchId().toString());
	jGen.writeStringField("port", spb.getSwitchPort().toString());
	jGen.writeStringField("updated", new Date(spb.getUpdateTime()).toString());
	jGen.writeStringField("bits-per-second-rx", spb.getBitsPerSecondRx().getBigInteger().toString());
	jGen.writeStringField("bits-per-second-tx", spb.getBitsPerSecondTx().getBigInteger().toString());
	jGen.writeEndObject();
}
 
Example 24
Project: athena   File: UuidSerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(Uuid value, JsonGenerator generator,
                      SerializerProvider provider) throws IOException {
    generator.writeStartArray();
    String reg = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
    if (value.value().matches(reg)) {
        generator.writeString("uuid");
    } else {
        generator.writeString("named-uuid");
    }
    generator.writeString(value.value());
    generator.writeEndArray();
}
 
Example 25
Project: azeroth   File: DateConvertSerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(Date date, JsonGenerator jgen,
                      SerializerProvider provider) throws JsonProcessingException {
    try {
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        jgen.writeString(dateFormat.format(date));
    } catch (IOException e) {
        throw new RuntimeException("Date转换json异常,格式:" + pattern);
    }
    //		log.debug("日期类型序列化");
}
 
Example 26
Project: OperatieBRP   File: BerichtDetailSerializer.java   View source code 5 votes vote down vote up
private void schrijfBerichtStuurgegevens(final JsonGenerator jgen, final BerichtDetailView value) throws IOException {
    JsonUtils.writeAsInteger(jgen, BerichtModule.ID, ObjectUtils.getWaarde(value, "bericht.id"));
    JsonUtils.writeAsInteger(jgen, BerichtModule.SOORT, ObjectUtils.getWaarde(value, "bericht.soortBericht.id"));
    JsonUtils.writeAsString(jgen, BerichtModule.SOORT_NAAM, ObjectUtils.getWaarde(value, "bericht.soortBericht.identifier"));
    JsonUtils.writeAsInteger(jgen, BerichtModule.ZENDENDE_PARTIJ, ObjectUtils.getWaarde(value, "bericht.zendendePartij"));
    JsonUtils.writeAsInteger(jgen, BerichtModule.ONTVANGENDE_PARTIJ, ObjectUtils.getWaarde(value, "bericht.ontvangendePartij"));
    JsonUtils.writeAsString(jgen, BerichtModule.REFERENTIENUMMER, value.getBericht().getReferentieNummer());
    JsonUtils.writeAsString(jgen, BerichtModule.CROSS_REFERENTIENUMMER, value.getBericht().getCrossReferentieNummer());
    JsonUtils.writeAsString(jgen, BerichtModule.VERZENDDATUM, ObjectUtils.getGeformateerdeWaarde(value, "bericht.datumTijdVerzending", sdf));
    JsonUtils.writeAsString(jgen, BerichtModule.ONTVANGSTDATUM, ObjectUtils.getGeformateerdeWaarde(value, "bericht.datumTijdOntvangst", sdf));
}
 
Example 27
Project: beadledom   File: FieldFilter.java   View source code 5 votes vote down vote up
private void processStructStart(JsonToken token, JsonGenerator jgen) throws IOException {
  if (token.id() == JsonToken.START_OBJECT.id()) {
    jgen.writeStartObject();
  } else if (token.id() == JsonToken.START_ARRAY.id()) {
    jgen.writeStartArray();
  } else {
    LOGGER.error("Illegal struct start {}", token.id());
    throw new RuntimeException("Illegal struct start " + token.id());
  }
}
 
Example 28
Project: iTAP-controller   File: StatsReplySerializer.java   View source code 5 votes vote down vote up
public static void serializePortReply(List<OFPortStatsReply> portReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
	OFPortStatsReply portReply = portReplies.get(0); // we will get only one PortReply and it will contains many OFPortStatsEntry ?
	jGen.writeStringField("version", portReply.getVersion().toString()); //return the enum name
	jGen.writeFieldName("port");
	jGen.writeStartArray();
	for(OFPortStatsEntry entry : portReply.getEntries()) {
		jGen.writeStartObject();
		jGen.writeStringField("portNumber",entry.getPortNo().toString());
		jGen.writeNumberField("receivePackets", entry.getRxPackets().getValue());
		jGen.writeNumberField("transmitPackets", entry.getTxPackets().getValue());
		jGen.writeNumberField("receiveBytes", entry.getRxBytes().getValue());
		jGen.writeNumberField("transmitBytes", entry.getTxBytes().getValue());
		jGen.writeNumberField("receiveDropped", entry.getRxDropped().getValue());
		jGen.writeNumberField("transmitDropped", entry.getTxDropped().getValue());
		jGen.writeNumberField("receiveErrors", entry.getRxErrors().getValue());
		jGen.writeNumberField("transmitErrors", entry.getTxErrors().getValue());
		jGen.writeNumberField("receiveFrameErrors", entry.getRxFrameErr().getValue());
		jGen.writeNumberField("receiveOverrunErrors", entry.getRxOverErr().getValue());
		jGen.writeNumberField("receiveCRCErrors", entry.getRxCrcErr().getValue());
		jGen.writeNumberField("collisions", entry.getCollisions().getValue());
		if (OFVersion.OF_13 == entry.getVersion()) {
			jGen.writeNumberField("durationSec", entry.getDurationSec());
			jGen.writeNumberField("durationNsec", entry.getDurationNsec());
		}
		jGen.writeEndObject();
	}
	jGen.writeEndArray();
}
 
Example 29
Project: alfresco-remote-api   File: JsonJacksonTests.java   View source code 5 votes vote down vote up
@Test
public void testSerializeMultipleObjects() throws IOException
{
    final Collection<Comment> allComments = new ArrayList<Comment>();
    Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    allComments.add(aComment);
    aComment = new Comment();
    aComment.setContent("<p>I agree with the author</p>");
    allComments.add(aComment);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, allComments);
        }
    });
    assertTrue(out.toString().contains("content\":\"<b>There it is</b>"));
    assertTrue(out.toString().contains("content\":\"<p>I agree with the author</p>"));
}
 
Example 30
Project: GitHub   File: DefaultIndenter.java   View source code 5 votes vote down vote up
@Override
public void writeIndentation(JsonGenerator jg, int level) throws IOException
{
    jg.writeRaw(eol);
    if (level > 0) { // should we err on negative values (as there's some flaw?)
        level *= charsPerLevel;
        while (level > indents.length) { // unlike to happen but just in case
            jg.writeRaw(indents, 0, indents.length); 
            level -= indents.length;
        }
        jg.writeRaw(indents, 0, level);
    }
}
 
Example 31
Project: fresco_floodlight   File: IOFSwitchSerializer.java   View source code 5 votes vote down vote up
public void serializeActions(Set<OFActionType> actions, JsonGenerator jGen)
        throws IOException, JsonProcessingException {
    if ( null == actions)
        jGen.writeStringField("actions","null");
    else{
        jGen.writeFieldName("actions");
        jGen.writeStartArray();
        for(OFActionType action : actions){
            jGen.writeString(action.toString());
        }
        jGen.writeEndArray();
    }
}
 
Example 32
Project: jackson-dataformat-velocypack   File: VPackSerializeDeserializeTest.java   View source code 5 votes vote down vote up
@Test
public void customSerializerWithContext() throws IOException {
	final SimpleModule module = new SimpleModule();
	module.addSerializer(TestEntityObject.class, new JsonSerializer<TestEntityObject>() {
		@Override
		public void serialize(
			final TestEntityObject value,
			final JsonGenerator gen,
			final SerializerProvider serializers) throws IOException, JsonProcessingException {
			gen.writeStartObject();
			serializers.defaultSerializeField("test", value.o1, gen);
			gen.writeEndObject();
		}
	});
	final ObjectMapper mapper = new VPackMapper().registerModule(module);
	final TestEntityObject entity = new TestEntityObject();
	final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(entity));
	assertThat(vpack, is(notNullValue()));
	assertThat(vpack.isObject(), is(true));
	{
		final VPackSlice test = vpack.get("test");
		assertThat(test.isObject(), is(true));
		final VPackSlice l1 = test.get("l1");
		assertThat(l1.isInteger(), is(true));
		assertThat(l1.getAsInt(), is(1));
	}
}
 
Example 33
Project: powsybl-core   File: NodeDependencySerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(NodeDependency dependency, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField("name", dependency.getName());
    jsonGenerator.writeFieldName("nodeInfo");
    new NodeInfoJsonSerializer().serialize(dependency.getNodeInfo(), jsonGenerator, serializerProvider);
    jsonGenerator.writeEndObject();
}
 
Example 34
Project: iextrading4j   File: SystemEventTypeSerializerTest.java   View source code 5 votes vote down vote up
@Test
public void shouldWriteNullIfValueIsUnknown() throws IOException {
    final JsonGenerator jsonGeneratorMock = mock(JsonGenerator.class);
    final SerializerProvider serializerProviderMock = mock(SerializerProvider.class);
    final SystemEventType input = SystemEventType.UNKNOWN;

    systemEventTypeSerializer.serialize(input, jsonGeneratorMock, serializerProviderMock);

    verify(jsonGeneratorMock).writeNull();
}
 
Example 35
Project: iextrading4j   File: TradingStatusTypeSerializerTest.java   View source code 5 votes vote down vote up
@Test
public void shouldWriteNullIfValueIsUnknown() throws IOException {
    final JsonGenerator jsonGeneratorMock = mock(JsonGenerator.class);
    final SerializerProvider serializerProviderMock = mock(SerializerProvider.class);
    final TradingStatusType input = TradingStatusType.UNKNOWN;

    tradingStatusTypeSerializer.serialize(input, jsonGeneratorMock, serializerProviderMock);

    verify(jsonGeneratorMock).writeNull();
}
 
Example 36
Project: koryphe   File: SimpleClassSerializerTest.java   View source code 5 votes vote down vote up
@Test
public void shouldSerialiseToFullClassNameWhenUnknown() throws IOException, ClassNotFoundException {
    // Given
    SimpleClassNameCache.setUseFullNameForSerialisation(false);
    final SimpleClassSerializer serialiser = new SimpleClassSerializer();
    final JsonGenerator jgen = mock(JsonGenerator.class);
    final Class clazz = UnsignedLong.class;

    // When
    serialiser.serialize(clazz, jgen, null);

    // Then
    verify(jgen).writeString(clazz.getName());
}
 
Example 37
Project: curiostack   File: SerializeSupport.java   View source code 5 votes vote down vote up
static void printRepeatedString(List<String> values, JsonGenerator gen) throws IOException {
  int numElements = values.size();
  gen.writeStartArray(numElements);
  for (int i = 0; i < numElements; i++) {
    printString(values.get(i), gen);
  }
  gen.writeEndArray();
}
 
Example 38
Project: beaker-notebook-archive   File: TableDisplayAlignmentSerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(TableDisplayAlignmentProvider value,
                      JsonGenerator jgen,
                      SerializerProvider provider)
  throws IOException, JsonProcessingException {

  synchronized (value) {
    jgen.writeString(value.getCode());
  }
}
 
Example 39
Project: dremio-oss   File: JSONOptions.java   View source code 5 votes vote down vote up
@Override
public void serialize(JSONOptions value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
    JsonGenerationException {
  if (value.opaque != null) {
    jgen.writeObject(value.opaque);
  } else {
    jgen.writeTree(value.root);
  }

}
 
Example 40
Project: beaker-notebook-archive   File: BasicObjectSerializer.java   View source code 5 votes vote down vote up
@Override
public boolean writeObject(Object obj, JsonGenerator jgen, boolean expand) throws JsonProcessingException, IOException {
  logger.debug("list of maps");
  try {
    // convert this 'on the fly' to a datatable
    @SuppressWarnings("unchecked")
    Collection<Map<?, ?>> co = (Collection<Map<?, ?>>) obj;
    TableDisplay t = new TableDisplay(co,parent);
    jgen.writeObject(t);
    return true;
  } catch(Exception e) {
    return false;
  }
}