Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#writeStartObject()

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator#writeStartObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writeComplexCollection(final ServiceMetadata metadata, final EdmComplexType type,
    final Property property,
    final Set<List<String>> selectedPaths, final JsonGenerator json)
    throws IOException, SerializerException {
  json.writeStartArray();
  for (Object value : property.asCollection()) {
    switch (property.getValueType()) {
    case COLLECTION_COMPLEX:
      json.writeStartObject();
      if (isODataMetadataFull) {
        json.writeStringField(Constants.JSON_TYPE, "#" +
            type.getFullQualifiedName().getFullQualifiedNameAsString());
      }
      writeComplexValue(metadata, type, ((ComplexValue) value).getValue(), selectedPaths, json);
      json.writeEndObject();
      break;
    default:
      throw new SerializerException("Property type not yet supported!",
          SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
    }
  }
  json.writeEndArray();
}
 
Example 2
Source File: CoordinatedClusterSerializer.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize( final ICoordinatedCluster value, final JsonGenerator jgen,
                       final SerializerProvider provider ) throws IOException {

    jgen.writeStartObject();

    jgen.writeStringField( NAME, value.getName() );
    jgen.writeNumberField( SIZE, value.getSize() );
    jgen.writeObjectField( INSTANCE_SPEC, value.getInstanceSpec() );

    jgen.writeArrayFieldStart( INSTANCES );

    for( Instance instance: value.getInstances() ) {
        jgen.writeObject( instance );
    }

    jgen.writeEndArray();

    jgen.writeEndObject();
}
 
Example 3
Source File: Bean8BindMap.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJackson(Bean8 object, JsonGenerator jacksonSerializer) throws Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field id (mapped with "id")
  fieldCount++;
  jacksonSerializer.writeNumberField("id", object.id);

  // field ignore2 (mapped with "ignore2")
  if (object.ignore2!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("ignore2", object.ignore2);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example 4
Source File: UKResultMapper.java    From youkefu with Apache License 2.0 6 votes vote down vote up
private String buildJSONFromFields(Collection<SearchHitField> values) {
	JsonFactory nodeFactory = new JsonFactory();
	try {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
		generator.writeStartObject();
		for (SearchHitField value : values) {
			if (value.getValues().size() > 1) {
				generator.writeArrayFieldStart(value.getName());
				for (Object val : value.getValues()) {
					generator.writeObject(val);
				}
				generator.writeEndArray();
			} else {
				generator.writeObjectField(value.getName(), value.getValue());
			}
		}
		generator.writeEndObject();
		generator.flush();
		return new String(stream.toByteArray(), Charset.forName("UTF-8"));
	} catch (IOException e) {
		return null;
	}
}
 
Example 5
Source File: UriSerializer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(String id, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("id", id);
    jgen.writeFieldName("uri");
    jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id));
    jgen.writeEndObject();
}
 
Example 6
Source File: UsersStreamSerializer.java    From java-json-benchmark with MIT License 5 votes vote down vote up
@Override
public void jackson(JsonGenerator j, Users obj) throws IOException {
    j.writeStartObject();
    if (obj.users != null) {
        j.writeFieldName("users");
        j.writeStartArray();
        for (User u : obj.users) {
            jackson(j, u);
        }
        j.writeEndArray();
    }
    j.writeEndObject();
}
 
Example 7
Source File: CharBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value2 serialization
 */
public static byte[] serializeValue2(Character[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      int n=value.length;
      Character item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 8
Source File: Bean93BindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Bean93 object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field id (mapped with "id")
  jacksonSerializer.writeStringField("id", PrimitiveUtils.writeLong(object.id));

  // field name (mapped with "name")
  if (object.name!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("name", object.name);
  }

  // field surname (mapped with "surname")
  if (object.surname!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("surname", object.surname);
  }

  // field typeName (mapped with "typeName")
  if (object.typeName!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("typeName", object.typeName);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example 9
Source File: ExtractionDimensionSpec.java    From Quicksql with MIT License 5 votes vote down vote up
@Override public void write(JsonGenerator generator) throws IOException {
  generator.writeStartObject();
  generator.writeStringField("type", "extraction");
  generator.writeStringField("dimension", dimension);
  writeFieldIf(generator, "outputName", outputName);
  writeField(generator, "extractionFn", extractionFunction);
  generator.writeEndObject();
}
 
Example 10
Source File: JRTServerConfigRequestV3.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public void addErrorResponse(int errorCode, String name) {
    ByteArrayOutputStream byteArrayOutputStream = new NoCopyByteArrayOutputStream();
    try {
        JsonGenerator jsonWriter = jsonFactory.createGenerator(byteArrayOutputStream);
        jsonWriter.writeStartObject();
        addCommonReturnValues(jsonWriter);
        jsonWriter.writeEndObject();
        jsonWriter.close();
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not add error response for " + this);
    }
    request.setError(errorCode, name);
    request.returnValues().add(createResponseValue(byteArrayOutputStream));
}
 
Example 11
Source File: ReplicaLocation.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes contents into YAML representation Sample representation below
 *
 * <pre>
 * lfn: "f2"
 * pfns:
 *   -
 *     pfn: "file:///path/to/file"
 *     site: "local"
 *   -
 *     pfn: "file:///path/to/file"
 *     site: "condorpool"
 * checksum:
 *   sha256: "991232132abc"
 * metadata:
 *   owner: "pegasus"
 *   abc: "123"
 *   size: "1024"
 *   k: "v"
 * </pre>
 *
 * @param r;
 * @param gen
 * @param sp
 * @throws IOException
 */
public void serialize(ReplicaLocation rl, JsonGenerator gen, SerializerProvider sp)
        throws IOException {
    gen.writeStartObject();
    writeStringField(gen, ReplicaCatalogKeywords.LFN.getReservedName(), rl.getLFN());
    if (rl.isRegex()) {
        writeStringField(gen, ReplicaCatalogKeywords.REGEX.getReservedName(), "true");
    }
    if (rl.getPFNCount() > 0) {
        gen.writeArrayFieldStart(ReplicaCatalogKeywords.PFNS.getReservedName());
        for (ReplicaCatalogEntry rce : rl.getPFNList()) {
            gen.writeStartObject();
            // we don't quote or escape anything as serializer
            // always adds enclosing quotes
            writeStringField(
                    gen, ReplicaCatalogKeywords.PFN.getReservedName(), rce.getPFN());
            writeStringField(
                    gen,
                    ReplicaCatalogKeywords.SITE.getReservedName(),
                    rce.getResourceHandle());
            gen.writeEndObject();
        }
        gen.writeEndArray();
    }
    Metadata m = rl.getAllMetadata();
    if (m != null && !m.isEmpty()) {
        gen.writeObject(m);
    }

    gen.writeEndObject();
}
 
Example 12
Source File: Bean2Table.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueCharacterSet serialization
 */
public static byte[] serializeValueCharacterSet(Set<Character> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (Character item: value) {
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 13
Source File: HttpTestServer.java    From crate with Apache License 2.0 5 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest msg) throws UnsupportedEncodingException {
    String uri = msg.uri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    logger.debug("Got Request for " + uri);
    HttpResponseStatus status = fail ? HttpResponseStatus.BAD_REQUEST : HttpResponseStatus.OK;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
            if (entry.getValue().size() == 1) {
                generator.writeStringField(entry.getKey(), URLDecoder.decode(entry.getValue().get(0), "UTF-8"));
            } else {
                generator.writeArrayFieldStart(entry.getKey());
                for (String value : entry.getValue()) {
                    generator.writeString(URLDecoder.decode(value, "UTF-8"));
                }
                generator.writeEndArray();
            }
        }
        generator.writeEndObject();
        generator.close();

    } catch (Exception ex) {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    ByteBuf byteBuf = Unpooled.wrappedBuffer(out.toByteArray());
    responses.add(out.toString(StandardCharsets.UTF_8.name()));

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
    ChannelFuture future = ctx.channel().writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 14
Source File: SafeReplaceOperation.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeStartObject();
    gen.writeStringField("op", op);
    gen.writeStringField("path", path.toString());
    gen.writeFieldName("oldValue");
    gen.writeTree(oldValue);
    gen.writeFieldName("value");
    gen.writeTree(newValue);
    gen.writeEndObject();
}
 
Example 15
Source File: ByteDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for param serializer2 serialization
 */
private byte[] serializer2(List<Byte> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    jacksonSerializer.writeStartObject();
    if (value!=null)  {
      int n=value.size();
      Byte item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value.get(i);
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 16
Source File: RDFJSONWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Helper method to reduce complexity of the JSON serialisation algorithm Any null contexts will only be serialised
 * to JSON if there are also non-null contexts in the contexts array
 *
 * @param object   The RDF value to serialise
 * @param contexts The set of contexts that are relevant to this object, including null contexts as they are found.
 * @param jg       the {@link JsonGenerator} to write to.
 * @throws IOException
 * @throws JsonGenerationException
 * @throws JSONException
 */
public static void writeObject(final Value object, final Set<Resource> contexts, final JsonGenerator jg)
		throws JsonGenerationException, IOException {
	jg.writeStartObject();
	if (object instanceof Literal) {
		jg.writeObjectField(RDFJSONUtility.VALUE, object.stringValue());

		jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.LITERAL);
		final Literal l = (Literal) object;

		if (Literals.isLanguageLiteral(l)) {
			jg.writeObjectField(RDFJSONUtility.LANG, l.getLanguage().orElse(null));
		} else {
			jg.writeObjectField(RDFJSONUtility.DATATYPE, l.getDatatype().stringValue());
		}
	} else if (object instanceof BNode) {
		jg.writeObjectField(RDFJSONUtility.VALUE, resourceToString((BNode) object));

		jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.BNODE);
	} else if (object instanceof IRI) {
		jg.writeObjectField(RDFJSONUtility.VALUE, resourceToString((IRI) object));

		jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.URI);
	}

	if (contexts != null && !contexts.isEmpty() && !(contexts.size() == 1 && contexts.iterator().next() == null)) {
		jg.writeArrayFieldStart(RDFJSONUtility.GRAPHS);
		for (final Resource nextContext : contexts) {
			if (nextContext == null) {
				jg.writeNull();
			} else {
				jg.writeString(resourceToString(nextContext));
			}
		}
		jg.writeEndArray();
	}

	jg.writeEndObject();
}
 
Example 17
Source File: BufferedImageSerializer.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(BufferedImage v, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonProcessingException {
  synchronized(v) {
    byte [] data = Images.encode(v);
    jgen.writeStartObject();
    jgen.writeStringField("type",  "ImageIcon");
    jgen.writeObjectField("imageData", data);
    jgen.writeNumberField("width", v.getWidth());
    jgen.writeNumberField("height", v.getHeight());
    jgen.writeEndObject();
  }
}
 
Example 18
Source File: BeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueEnumTypeSet serialization
 */
public static byte[] serializeValueEnumTypeSet(HashSet<EnumType> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (EnumType item: value) {
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeString(item.toString());
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 19
Source File: ExportCOCOController.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
private void writeAnnotation(JsonGenerator writer, ObjectModel model, int id, int imageId, Map<String, Integer> categoryMap) throws IOException {
   writer.writeStartObject();
   writer.writeNumberField("id", id);

   // Resolve categories and category IDs
   var category = model.getName();
   var categoryId = categoryMap.get(category);
   if (categoryId == null) {
      categoryId = categoryMap.entrySet().size() + 1;
      categoryMap.put(category, categoryId);
   }
   writer.writeNumberField("category_id", categoryId);

   writer.writeNumberField("image_id", imageId);
   writer.writeNumberField("iscrowd", 0);

   BoundBox bb = model.getBoundBox();
   writer.writeArrayFieldStart("segmentation");
   double[] points = new double[]{bb.getXMin(), bb.getYMin(), bb.getXMax(), bb.getYMax()};
   if (model.getPolygon() != null) {
      points = model.getPolygon().stream().mapToDouble(Double::doubleValue).toArray();
   }
   writer.writeArray(points, 0, points.length);
   writer.writeEndArray();

   writer.writeNumberField("area", model.area());
   writer.writeObjectField("bbox", new double[]{bb.getX(), bb.getY(), bb.getWidth(), bb.getHeight()});

   writer.writeEndObject();
}
 
Example 20
Source File: CountryBindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Country object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field area (mapped with "area")
  jacksonSerializer.writeStringField("area", PrimitiveUtils.writeLong(object.area));

  // field callingCode (mapped with "callingCode")
  if (object.callingCode!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("callingCode", object.callingCode);
  }

  // field code (mapped with "code")
  if (object.code!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("code", object.code);
  }

  // field id (mapped with "id")
  jacksonSerializer.writeStringField("id", PrimitiveUtils.writeLong(object.id));

  // field name (mapped with "name")
  if (object.name!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("name", object.name);
  }

  // field region (mapped with "region")
  if (object.region!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("region", object.region);
  }

  // field translatedName (mapped with "translatedName")
  if (object.translatedName!=null)  {
    fieldCount++;
    // write wrapper tag
    if (object.translatedName.size()>0) {
      jacksonSerializer.writeFieldName("translatedName");
      jacksonSerializer.writeStartArray();
      for (Map.Entry<Translation, String> item: object.translatedName.entrySet()) {
        jacksonSerializer.writeStartObject();
        jacksonSerializer.writeStringField("key", item.getKey().toString());
        if (item.getValue()==null) {
          jacksonSerializer.writeStringField("value", "null");
        } else {
          jacksonSerializer.writeStringField("value", item.getValue());
        }
        jacksonSerializer.writeEndObject();
      }
      jacksonSerializer.writeEndArray();
    } else {
      jacksonSerializer.writeStringField("translatedName", "null");
    }
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}