public void jacksonTest() throws Exception { JsonFactory factory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createJsonGenerator(writer); generator.writeStartObject(); generator.writeFieldName("bool"); generator.writeBoolean(true); generator.writeFieldName("firstName"); generator.writeString("john"); generator.writeFieldName("age"); generator.writeNumber(1); generator.writeFieldName("gg"); generator.writeStartObject(); generator.writeFieldName("firstName"); generator.writeString("john"); generator.writeEndObject(); generator.writeEndObject(); generator.close(); String generated = writer.toString(); System.out.print(generated); JsonParser parser = factory.createJsonParser(generated); assertTrue(parser.nextToken() == JsonToken.START_OBJECT); parser.nextToken(); assertEquals("bool", parser.getCurrentName()); assertTrue(parser.nextToken() == JsonToken.VALUE_TRUE); parser.nextToken(); assertEquals("firstName", parser.getCurrentName()); parser.nextToken(); assertEquals("john", parser.getText()); parser.nextToken(); assertEquals("age", parser.getCurrentName()); parser.nextToken(); assertTrue(1 == parser.getIntValue()); parser.nextToken(); assertEquals("gg", parser.getCurrentName()); assertTrue(parser.nextToken() == JsonToken.START_OBJECT); parser.nextToken(); assertEquals("firstName", parser.getCurrentName()); parser.nextToken(); assertEquals("john", parser.getText()); assertTrue(parser.nextToken() == JsonToken.END_OBJECT); assertTrue(parser.nextToken() == JsonToken.END_OBJECT); parser.close(); }
private void writeScalarPropertyValue(JsonGenerator jg, Type type, Object value) throws IOException { if (value == null) { jg.writeNull(); } else if (type instanceof BooleanType) { jg.writeBoolean((Boolean) value); } else if (type instanceof LongType) { jg.writeNumber((Long) value); } else if (type instanceof DoubleType) { jg.writeNumber((Double) value); } else if (type instanceof IntegerType) { jg.writeNumber((Integer) value); } else if (type instanceof BinaryType) { jg.writeBinary((byte[]) value); } else { jg.writeString(type.encode(value)); } }