Search in sources :

Example 26 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class ObjectMapper method _convert.

/**
     * Actual conversion implementation: instead of using existing read
     * and write methods, much of code is inlined. Reason for this is
     * that we must avoid root value wrapping/unwrapping both for efficiency and
     * for correctness. If root value wrapping/unwrapping is actually desired,
     * caller must use explicit <code>writeValue</code> and
     * <code>readValue</code> methods.
     */
@SuppressWarnings("resource")
protected Object _convert(Object fromValue, JavaType toValueType) throws IllegalArgumentException {
    // This defaults primitives and fires deserializer getNullValue hooks.
    if (fromValue != null) {
        // also, as per [databind#11], consider case for simple cast
        // But with caveats: one is that while everything is Object.class, we don't
        // want to "optimize" that out; and the other is that we also do not want
        // to lose conversions of generic types.
        Class<?> targetType = toValueType.getRawClass();
        if (targetType != Object.class && !toValueType.hasGenericTypes() && targetType.isAssignableFrom(fromValue.getClass())) {
            return fromValue;
        }
    }
    // Then use TokenBuffer, which is a JsonGenerator:
    TokenBuffer buf = new TokenBuffer(this, false);
    if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
        buf = buf.forceUseOfBigDecimal(true);
    }
    try {
        // inlined 'writeValue' with minor changes:
        // first: disable wrapping when writing
        SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE);
        // no need to check for closing of TokenBuffer
        _serializerProvider(config).serializeValue(buf, fromValue);
        // then matching read, inlined 'readValue' with minor mods:
        final JsonParser p = buf.asParser();
        Object result;
        // ok to pass in existing feature flags; unwrapping handled by mapper
        final DeserializationConfig deserConfig = getDeserializationConfig();
        JsonToken t = _initForReading(p, toValueType);
        if (t == JsonToken.VALUE_NULL) {
            DeserializationContext ctxt = createDeserializationContext(p, deserConfig);
            result = _findRootDeserializer(ctxt, toValueType).getNullValue(ctxt);
        } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
            result = null;
        } else {
            // pointing to event other than null
            DeserializationContext ctxt = createDeserializationContext(p, deserConfig);
            JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, toValueType);
            // note: no handling of unwrapping
            result = deser.deserialize(p, ctxt);
        }
        p.close();
        return result;
    } catch (IOException e) {
        // should not occur, no real i/o...
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Example 27 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class ObjectMapper method valueToTree.

/**
     * Reverse of {@link #treeToValue}; given a value (usually bean), will
     * construct equivalent JSON Tree representation. Functionally similar
     * to serializing value into JSON and parsing JSON as tree, but
     * more efficient.
     *<p>
     * NOTE: while results are usually identical to that of serialization followed
     * by deserialization, this is not always the case. In some cases serialization
     * into intermediate representation will retain encapsulation of things like
     * raw value ({@link com.fasterxml.jackson.databind.util.RawValue}) or basic
     * node identity ({@link JsonNode}). If so, result is a valid tree, but values
     * are not re-constructed through actual JSON representation. So if transformation
     * requires actual materialization of JSON (or other data format that this mapper
     * produces), it will be necessary to do actual serialization.
     * 
     * @param <T> Actual node type; usually either basic {@link JsonNode} or
     *  {@link com.fasterxml.jackson.databind.node.ObjectNode}
     * @param fromValue Bean value to convert
     * @return Root node of the resulting JSON tree
     */
@SuppressWarnings({ "unchecked", "resource" })
public <T extends JsonNode> T valueToTree(Object fromValue) throws IllegalArgumentException {
    if (fromValue == null)
        return null;
    TokenBuffer buf = new TokenBuffer(this, false);
    if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
        buf = buf.forceUseOfBigDecimal(true);
    }
    JsonNode result;
    try {
        writeValue(buf, fromValue);
        JsonParser p = buf.asParser();
        result = readTree(p);
        p.close();
    } catch (IOException e) {
        // should not occur, no real i/o...
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    return (T) result;
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Example 28 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class JDKStringLikeTypesTest method testUUIDAux.

public void testUUIDAux() throws Exception {
    // [JACKSON-393] fix:
    final UUID value = UUID.fromString("76e6d183-5f68-4afa-b94a-922c1fdb83f8");
    // first, null should come as null
    TokenBuffer buf = new TokenBuffer(null, false);
    buf.writeObject(null);
    assertNull(MAPPER.readValue(buf.asParser(), UUID.class));
    buf.close();
    // then, UUID itself come as is:
    buf = new TokenBuffer(null, false);
    buf.writeObject(value);
    assertSame(value, MAPPER.readValue(buf.asParser(), UUID.class));
    // and finally from byte[]
    // oh crap; JDK UUID just... sucks. Not even byte[] accessors or constructors? Huh?
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bytes);
    out.writeLong(value.getMostSignificantBits());
    out.writeLong(value.getLeastSignificantBits());
    byte[] data = bytes.toByteArray();
    assertEquals(16, data.length);
    buf.writeObject(data);
    UUID value2 = MAPPER.readValue(buf.asParser(), UUID.class);
    assertEquals(value, value2);
    buf.close();
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer) UUID(java.util.UUID)

Example 29 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class JDKStringLikeTypesTest method testURL.

public void testURL() throws Exception {
    URL exp = new URL("http://foo.com");
    assertEquals(exp, MAPPER.readValue("\"" + exp.toString() + "\"", URL.class));
    // trivial case; null to null, embedded URL to URL
    TokenBuffer buf = new TokenBuffer(null, false);
    buf.writeObject(null);
    assertNull(MAPPER.readValue(buf.asParser(), URL.class));
    buf.close();
    // then, URLitself come as is:
    buf = new TokenBuffer(null, false);
    buf.writeObject(exp);
    assertSame(exp, MAPPER.readValue(buf.asParser(), URL.class));
    buf.close();
    // and finally, invalid URL should be handled appropriately too
    try {
        URL result = MAPPER.readValue(quote("a b"), URL.class);
        fail("Should not accept malformed URI, instead got: " + result);
    } catch (InvalidFormatException e) {
        verifyException(e, "not a valid textual representation");
    }
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException)

Example 30 with TokenBuffer

use of com.fasterxml.jackson.databind.util.TokenBuffer in project jackson-databind by FasterXML.

the class TestJacksonTypes method testTokenBufferWithSample.

/**
     * Verify that {@link TokenBuffer} can be properly deserialized
     * automatically, using the "standard" JSON sample document
     */
public void testTokenBufferWithSample() throws Exception {
    ObjectMapper m = new ObjectMapper();
    // First, try standard sample doc:
    TokenBuffer result = m.readValue(SAMPLE_DOC_JSON_SPEC, TokenBuffer.class);
    verifyJsonSpecSampleDoc(result.asParser(), true);
    result.close();
}
Also used : TokenBuffer(com.fasterxml.jackson.databind.util.TokenBuffer)

Aggregations

TokenBuffer (com.fasterxml.jackson.databind.util.TokenBuffer)37 IOException (java.io.IOException)11 JsonParser (com.fasterxml.jackson.core.JsonParser)3 RexLiteral (org.apache.calcite.rex.RexLiteral)3 NlsString (org.apache.calcite.util.NlsString)3 ExtendedJsonOutput (org.apache.drill.exec.vector.complex.fn.ExtendedJsonOutput)3 JsonOutput (org.apache.drill.exec.vector.complex.fn.JsonOutput)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 DataBuffer (org.springframework.core.io.buffer.DataBuffer)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)1 SettableBeanProperty (com.fasterxml.jackson.databind.deser.SettableBeanProperty)1 InvalidFormatException (com.fasterxml.jackson.databind.exc.InvalidFormatException)1 UUID (java.util.UUID)1 Test (org.junit.jupiter.api.Test)1 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)1