Java Code Examples for com.fasterxml.jackson.databind.util.TokenBuffer#copyCurrentStructure()

The following examples show how to use com.fasterxml.jackson.databind.util.TokenBuffer#copyCurrentStructure() . 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: GuidedJsonDecoder.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Read a string from the current location in parser.
 *
 * <p>This method differs from the original JsonDecoder by serializing all
 * structures captured by the current token into a JSON string. This enables
 * consistent behavior for handling variant types (e.g. field that can be a
 * boolean and a string) and for under-specified schemas.
 *
 * <p>This encoding is lossy because JSON strings are conflated with standard
 * strings. Consider the case where a number is decoded into a string. To
 * convert this Avro file back into the original JSON document, the encoder
 * must parse all strings as JSON and inline them into the tree. Now, if the
 * original JSON represents a JSON object as a string (e.g. `{"payload":
 * "{\"foo\":\"bar\"}"`), then the encoder will generate a new object that is
 * different from the original.
 *
 * <p>There are a few ways to avoid this if it is undesirable. One way is to use
 * a binary encoding for the JSON data such as BSON or base64. A second is to
 * normalize documents to avoid nested JSON encodings and to specify a schema
 * explictly to guide the proper typing.
 */
@Override
public String readString() throws IOException {
  parser.advance(Symbol.STRING);
  if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) {
    parser.advance(Symbol.MAP_KEY_MARKER);
    assertCurrentToken(JsonToken.FIELD_NAME, "map-key");
  }

  String result = null;
  if (in.getCurrentToken() == JsonToken.VALUE_STRING
      || in.getCurrentToken() == JsonToken.FIELD_NAME) {
    result = in.getValueAsString();
  } else {
    // Does this create excessive garbage collection?
    TokenBuffer buffer = new TokenBuffer(in);
    buffer.copyCurrentStructure(in);
    result = mapper.readTree(buffer.asParser()).toString();
    buffer.close();
  }
  in.nextToken();
  return result;
}
 
Example 2
Source File: ExternalTypeHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("resource")
protected final Object _deserialize(JsonParser p, DeserializationContext ctxt,
        int index, String typeId) throws IOException
{
    JsonParser p2 = _tokens[index].asParser(p);
    JsonToken t = p2.nextToken();
    // 29-Sep-2015, tatu: As per [databind#942], nulls need special support
    if (t == JsonToken.VALUE_NULL) {
        return null;
    }
    TokenBuffer merged = new TokenBuffer(p, ctxt);
    merged.writeStartArray();
    merged.writeString(typeId);
    merged.copyCurrentStructure(p2);
    merged.writeEndArray();

    // needs to point to START_OBJECT (or whatever first token is)
    JsonParser mp = merged.asParser(p);
    mp.nextToken();
    return _properties[index].getProperty().deserialize(mp, ctxt);
}
 
Example 3
Source File: ExternalTypeHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("resource")
protected final void _deserializeAndSet(JsonParser p, DeserializationContext ctxt,
        Object bean, int index, String typeId) throws IOException
{
    /* Ok: time to mix type id, value; and we will actually use "wrapper-array"
     * style to ensure we can handle all kinds of JSON constructs.
     */
    JsonParser p2 = _tokens[index].asParser(p);
    JsonToken t = p2.nextToken();
    // 29-Sep-2015, tatu: As per [databind#942], nulls need special support
    if (t == JsonToken.VALUE_NULL) {
        _properties[index].getProperty().set(bean, null);
        return;
    }
    TokenBuffer merged = new TokenBuffer(p, ctxt);
    merged.writeStartArray();
    merged.writeString(typeId);

    merged.copyCurrentStructure(p2);
    merged.writeEndArray();
    // needs to point to START_OBJECT (or whatever first token is)
    JsonParser mp = merged.asParser(p);
    mp.nextToken();
    _properties[index].getProperty().deserializeAndSet(mp, ctxt, bean);
}
 
Example 4
Source File: BuilderBasedDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Object deserializeWithUnwrapped(JsonParser p,
        DeserializationContext ctxt, Object builder, TokenBuffer tokens)
    throws IOException
{
    final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null;
    for (JsonToken t = p.getCurrentToken(); t == JsonToken.FIELD_NAME; t = p.nextToken()) {
        String propName = p.getCurrentName();
        SettableBeanProperty prop = _beanProperties.find(propName);
        p.nextToken();
        if (prop != null) { // normal case
            if (activeView != null && !prop.visibleInView(activeView)) {
                p.skipChildren();
                continue;
            }
            try {
                builder = prop.deserializeSetAndReturn(p, ctxt, builder);
            } catch (Exception e) {
                wrapAndThrow(e, builder, propName, ctxt);
            }
            continue;
        }
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(p, ctxt, builder, propName);
            continue;
        }
        // but... others should be passed to unwrapped property deserializers
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(p);
        // how about any setter? We'll get copies but...
        if (_anySetter != null) {
            _anySetter.deserializeAndSet(p, ctxt, builder, propName);
        }
    }
    tokens.writeEndObject();
    return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, builder, tokens);
}
 
Example 5
Source File: JsonParserReader.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Reads current value including objects and array as effiecient token buffer.
 * Use of Jackson's own mechanisms is important to preserve custom elements
 * such as special embedded objects in BSON or other data formats.
 * @return {@link TokenBuffer}
 * @throws IOException if error occured
 */
public final TokenBuffer nextTokenBuffer() throws IOException {
  TokenBuffer buffer = new TokenBuffer(parser);
  // if token is consumed, but undelying parser is still sitting on this token, we move forward
  requirePeek();
  buffer.copyCurrentStructure(parser);
  // when we will return to reading from reader, state will be cleared and nextToken after
  clearPeek();
  return buffer;
}
 
Example 6
Source File: MetadataTypeResolver.java    From fahrschein with Apache License 2.0 4 votes vote down vote up
@Override
public Object deserializeTypedFromObject(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonToken t;

    t = p.getCurrentToken();
    if (t == JsonToken.START_OBJECT) {
        t = p.nextToken();
    } else if (t != JsonToken.FIELD_NAME) {
        throw new JsonMappingException(p, "Could not extract event type from non-object");
    }

    final TokenBuffer tb = new TokenBuffer(p, ctxt);

    for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
        final String topLevelProperty = p.getCurrentName();
        tb.writeFieldName(topLevelProperty);
        t = p.nextToken();
        if (topLevelProperty.equals("metadata")) {
            if (t != JsonToken.START_OBJECT) {
                throw new JsonMappingException(p, "Could not extract event type from invalid metadata");
            }
            tb.writeStartObject();
            t = p.nextToken();
            for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
                final String metadataProperty = p.getCurrentName();
                tb.writeFieldName(metadataProperty);
                t = p.nextToken();
                if (metadataProperty.equals("event_type")) {
                    if (t != JsonToken.VALUE_STRING) {
                        throw new JsonMappingException(p, "Could not extract event type from non-string property");
                    }
                    final String typeId = p.getText();
                    tb.writeString(typeId);
                    final JsonParser pb = JsonParserSequence.createFlattened(false, tb.asParser(p), p);
                    return deserialize(pb, ctxt, typeId);
                } else {
                    tb.copyCurrentStructure(p);
                }
            }
        } else {
            tb.copyCurrentStructure(p);
        }
    }
    throw new JsonMappingException(p, "Could not find metadata property to extract event type");
}