private static void writeValue(XContentGenerator gen, Object value) throws IOException {
   Class type = value.getClass();
   if (type == String.class) {
     gen.writeString((String) value);
   } else if (type == Integer.class) {
     gen.writeNumber(((Integer) value).intValue());
   } else if (type == Long.class) {
     gen.writeNumber(((Long) value).longValue());
   } else if (type == Float.class) {
     gen.writeNumber(((Float) value).floatValue());
   } else if (type == Double.class) {
     gen.writeNumber(((Double) value).doubleValue());
   } else if (type == Short.class) {
     gen.writeNumber(((Short) value).shortValue());
   } else if (type == Boolean.class) {
     gen.writeBoolean(((Boolean) value).booleanValue());
   } else if (value instanceof Map) {
     writeMap(gen, (Map) value);
   } else if (value instanceof Iterable) {
     writeIterable(gen, (Iterable) value);
   } else if (value instanceof Object[]) {
     writeObjectArray(gen, (Object[]) value);
   } else if (type == byte[].class) {
     gen.writeBinary((byte[]) value);
   } else if (value instanceof Date) {
     gen.writeString(XContentBuilder.defaultDatePrinter.print(((Date) value).getTime()));
   } else {
     gen.writeString(value.toString());
   }
 }
Ejemplo n.º 2
0
  @Test
  public void compareParsingTokens() throws IOException {
    BytesStreamOutput xsonOs = new BytesStreamOutput();
    XContentGenerator xsonGen =
        XContentFactory.xContent(XContentType.SMILE).createGenerator(xsonOs);

    BytesStreamOutput jsonOs = new BytesStreamOutput();
    XContentGenerator jsonGen = XContentFactory.xContent(XContentType.JSON).createGenerator(jsonOs);

    xsonGen.writeStartObject();
    jsonGen.writeStartObject();

    xsonGen.writeStringField("test", "value");
    jsonGen.writeStringField("test", "value");

    xsonGen.writeArrayFieldStart("arr");
    jsonGen.writeArrayFieldStart("arr");
    xsonGen.writeNumber(1);
    jsonGen.writeNumber(1);
    xsonGen.writeNull();
    jsonGen.writeNull();
    xsonGen.writeEndArray();
    jsonGen.writeEndArray();

    xsonGen.writeEndObject();
    jsonGen.writeEndObject();

    xsonGen.close();
    jsonGen.close();

    verifySameTokens(
        XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes().toBytes()),
        XContentFactory.xContent(XContentType.SMILE).createParser(xsonOs.bytes().toBytes()));
  }