Example usage for com.fasterxml.jackson.core JsonToken FIELD_NAME

List of usage examples for com.fasterxml.jackson.core JsonToken FIELD_NAME

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonToken FIELD_NAME.

Prototype

JsonToken FIELD_NAME

To view the source code for com.fasterxml.jackson.core JsonToken FIELD_NAME.

Click Source Link

Document

FIELD_NAME is returned when a String token is encountered as a field name (same lexical value, different function)

Usage

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * Method called to deserialize bean using "property-based creator":
 * this means that a non-default constructor or factory method is
 * called, and then possibly other setters. The trick is that
 * values for creator method need to be buffered, first; and
 * due to non-guaranteed ordering possibly some other properties
 * as well.//ww w.ja va 2 s .co  m
 */
@Override
@SuppressWarnings("resource")
protected Object _deserializeUsingPropertyBased(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {
    final PropertyBasedCreator creator = _propertyBasedCreator;
    PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt, _objectIdReader);

    // 04-Jan-2010, tatu: May need to collect unknown properties for polymorphic cases
    TokenBuffer unknown = null;

    JsonToken t = jp.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String propName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        // creator property?
        SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
        if (creatorProp != null) {
            // Last creator property to set?
            Object value = creatorProp.deserialize(jp, ctxt);
            if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                Object bean;
                try {
                    bean = creator.build(ctxt, buffer);
                } catch (Exception e) {
                    wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
                    bean = null; // never gets here
                }
                //  polymorphic?
                if (bean.getClass() != _beanType.getRawClass()) {
                    return handlePolymorphic(jp, ctxt, bean, unknown);
                }
                if (unknown != null) { // nope, just extra unknown stuff...
                    bean = handleUnknownProperties(ctxt, bean, unknown);
                }
                // or just clean?
                return deserialize(jp, ctxt, bean);
            }
            continue;
        }
        // Object Id property?
        if (buffer.readIdProperty(propName)) {
            continue;
        }

        // regular property? needs buffering
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            buffer.bufferProperty(prop, prop.deserialize(jp, ctxt));
            continue;
        }
        // As per [JACKSON-313], things marked as ignorable should not be
        // passed to any setter
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, handledType(), propName);
            continue;
        }
        // "any property"?
        if (_anySetter != null) {
            buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt));
            continue;
        }
        // Ok then, let's collect the whole field; name and value
        if (unknown == null) {
            unknown = new TokenBuffer(jp);
        }
        unknown.writeFieldName(propName);
        unknown.copyCurrentStructure(jp);
    }

    // We hit END_OBJECT, so:
    Object bean;
    try {
        bean = creator.build(ctxt, buffer);
    } catch (Exception e) {
        wrapInstantiationProblem(e, ctxt);
        bean = null; // never gets here
    }
    if (unknown != null) {
        // polymorphic?
        if (bean.getClass() != _beanType.getRawClass()) {
            return handlePolymorphic(null, ctxt, bean, unknown);
        }
        // no, just some extra unknown properties
        return handleUnknownProperties(ctxt, bean, unknown);
    }
    return bean;
}

From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

private void readEntity(String entityName) throws Exception {
    // Keeps track of whether the entity list starts with a [ or not.  If there
    // is no [ then we are done reading entities of this type when we find the
    // end of the object.
    boolean entityArray = false;
    int twinCount = 0;

    JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.START_ARRAY) {
        token = jp.nextToken();/*from  ww w .  jav a  2 s. co m*/
        entityArray = true; // Entity list started with [
    }

    assert token == JsonToken.START_OBJECT;

    EntityDef entityDef = lodDef.getEntityDef(entityName, true, true);

    // Read tokens until we find the token that ends the current list of entities.
    while ((token = jp.nextToken()) != null) {
        twinCount++;

        if (token == JsonToken.END_ARRAY)
            break;

        if (token == JsonToken.END_OBJECT) {
            // If we get here then this should indicate an empty OI.  Get the next
            // token, verify that it's an END_ARRAY, and return.
            token = jp.nextToken();
            assert token == JsonToken.END_ARRAY;
            break;
        }

        // If there are multiple twins then the token is START_OBJECT to
        // indicate a new EI.
        if (token == JsonToken.START_OBJECT) {
            assert twinCount > 1; // Assert that we already created at least one EI.
            token = jp.nextToken();
        }

        assert token == JsonToken.FIELD_NAME;
        EntityInstanceImpl ei = (EntityInstanceImpl) view.cursor(entityDef).createEntity(CursorPosition.LAST,
                CREATE_FLAGS);

        List<AttributeMeta> attributeMetas = new ArrayList<>();

        // Read tokens until we find the token that ends the current entity.
        EntityMeta entityMeta = DEFAULT_ENTITY_META;
        while ((token = jp.nextToken()) != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();

            if (token == JsonToken.FIELD_NAME || token == JsonToken.START_OBJECT)
                token = jp.nextToken();

            if (StringUtils.equals(fieldName, ".meta")) {
                entityMeta = readEntityMeta(ei);

                // Now that we have everything we can perform some processing.
                if (entityMeta.isLinkedSource)
                    linkSources.put(entityMeta.entityKey, ei);
                else if (entityMeta.linkedSource != null)
                    ei.linkInstances(linkSources.get(entityMeta.linkedSource));

                continue;
            }

            if (fieldName.startsWith(".")) {
                AttributeMeta am = readAttributeMeta(ei, fieldName);
                attributeMetas.add(am);
                continue;
            }

            // Is this the start of an entity.
            if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) {
                boolean recursiveChild = false;

                // Validate that the entity name is valid.
                EntityDef childEntity = lodDef.getEntityDef(fieldName, true, true);
                if (childEntity.getParent() != entityDef) {
                    // Check to see the childEntity is a recursive child.
                    if (entityDef.isRecursive()) {
                        view.cursor(entityDef).setToSubobject();
                        recursiveChild = true;
                    } else
                        throw new ZeidonException("Parse error: %s is not a child of %s", fieldName,
                                entityName);
                }

                readEntity(fieldName);

                if (recursiveChild)
                    view.resetSubobject();

                continue;
            }

            if (StringUtils.equals(jp.getText(), fieldName))
                // If jp points to attr name, get next token.
                token = jp.nextToken();

            // This better be an attribute
            // Try getting the attribute.  We won't throw an exception (yet) if there
            // is no attribute with a matching name.
            AttributeDef attributeDef = entityDef.getAttribute(fieldName, false, true);

            if (attributeDef == null) {
                // We didn't find an attribute with a name matching fieldName.  Do we allow
                // dynamic attributes for this entity?
                if (options.getAllowableDynamicEntities() == null
                        || !options.getAllowableDynamicEntities().contains(entityDef.getName())) {
                    entityDef.getAttribute(fieldName); // This will throw the exception.
                }

                // We are allowing dynamic attributes.  Create one.
                DynamicAttributeDefConfiguration config = new DynamicAttributeDefConfiguration();
                config.setAttributeName(fieldName);
                attributeDef = entityDef.createDynamicAttributeDef(config);
            } else if (attributeDef.isDerived()) // We'll ignore derived attributes.
                continue;

            Domain domain = attributeDef.getDomain();
            Object internalValue = domain.convertExternalValue(task, ei.getAttribute(attributeDef),
                    attributeDef, null, jp.getText());
            ei.getAttribute(attributeDef).setInternalValue(internalValue, !attributeDef.isKey());
            if (incremental) {
                // Since incremental flags are set, assume the attribute hasn't been
                // updated.  We'll be told later if it has.
                AttributeValue attrib = ei.getInternalAttribute(attributeDef);
                attrib.setUpdated(false);
            } else {
                // If we just set the key then we'll assume the entity has
                // already been created.
                if (attributeDef.isKey())
                    ei.setIncrementalFlags(IncrementalEntityFlags.UPDATED);
            }
        } // while ( ( token = jp.nextToken() ) != JsonToken.END_OBJECT )...

        // Apply all the attribute metas to correctly set the attribute flags.
        for (AttributeMeta am : attributeMetas)
            am.apply(ei);

        // Now that we've updated everything, set the flags.
        if (incremental) {
            ei.setCreated(entityMeta.created);
            ei.setUpdated(entityMeta.updated);
            ei.setDeleted(entityMeta.deleted);
            ei.setIncluded(entityMeta.included);
            ei.setExcluded(entityMeta.excluded);
            if (entityMeta.incomplete)
                ei.setIncomplete(null);
            if (entityMeta.lazyLoaded != null) {
                String[] names = entityMeta.lazyLoaded.split(",");
                for (String name : names)
                    ei.getEntitiesLoadedLazily().add(lodDef.getEntityDef(name, true, true));
            }
        }

        // If the entity list didn't start with a [ then there is only one entity
        // in the list of twins so exit.
        if (entityArray == false)
            break;

    } // while ( ( token = jp.nextToken() ) != null )...
}

From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java

@Nonnull
protected <T> T deserialize(@Nonnull Class<T> type, @Nonnull String propertyName,
        @Nonnull Version formatVersion, @Nonnull JsonParser deserializeFrom)
        throws IOException, JsonProcessingException {
    JacksonParserWrapper parserWrapper = new JacksonParserWrapper(deserializeFrom);
    parserWrapper.nextToken();//w w  w . ja  v  a  2s . c o m
    parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME);
    String currentName = parserWrapper.getCurrentName();

    if (!propertyName.equals(currentName)) {
        throw new JsonParseException(
                "Invalid field. Expected <" + propertyName + "> but was <" + currentName + ">",
                parserWrapper.getCurrentLocation());
    }
    parserWrapper.nextToken();
    return deserialize(type, formatVersion, deserializeFrom);
}

From source file:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final InputStream is) throws Exception {
    JsonParser jp = JSON.parseToStream(is);
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;//from w  w w.  ja va 2  s .  co  m
    while (jp.nextToken() != null) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName() != null) {
            field = jp.getCurrentName();
        } else if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            value = jp.getText();
            map.put(field, value);
        }
    }
    return map;
}

From source file:org.apache.lucene.server.handlers.AddDocumentHandler.java

/** Parses the fields, which should look like {field1:
 *  ..., field2: ..., ...} *///w w  w .jav  a  2s .c om
public static void parseFields(IndexState state, Document doc, JsonParser p) throws IOException {
    JsonToken token = p.nextToken();
    if (token != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("fields should be an object");
    }
    while (true) {
        token = p.nextToken();
        if (token == JsonToken.END_OBJECT) {
            break;
        }
        assert token == JsonToken.FIELD_NAME;
        parseOneField(p, state, doc, p.getText());
    }
}

From source file:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final JsonParser jp) throws Exception {
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;//ww w  .ja va  2 s  .c o  m
    while (jp.nextToken() != null) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName() != null) {
            field = jp.getCurrentName();
        } else if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            value = jp.getText();
            map.put(field, value);
        }
    }
    return map;
}

From source file:org.apache.lucene.server.handlers.AddDocumentHandler.java

/** Parse a Document using Jackson's streaming parser
 *  API.  The document should look like {indexName: 'foo',
 *  fields: {..., ...}} *//*from w  ww .ja  v  a2  s.co m*/
public static Document parseDocument(IndexState state, JsonParser p) throws IOException {
    JsonToken token = p.nextToken();
    if (token == JsonToken.END_ARRAY) {
        // nocommit hackish.. caller should tell us this means "end"?
        return null;
    } else if (token != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON Object");
    }

    final Document doc = new Document();
    while (true) {
        token = p.nextToken();
        if (token == JsonToken.END_OBJECT) {
            break;
        }
        assert token == JsonToken.FIELD_NAME : token;

        String fieldName = p.getText();
        if (fieldName.equals("fields")) {
            parseFields(state, doc, p);
        } else {
            // Let a plugin handle it:
            boolean handled = false;
            for (PostHandle postHandle : postHandlers) {
                if (postHandle.invoke(state, fieldName, p, doc)) {
                    handled = true;
                    break;
                }
            }

            if (!handled) {
                throw new IllegalArgumentException("unrecognized field " + p.getText());
            }
        }

        // nocommit need test that same field name can't
        // appear more than once?  app must put all values for
        // a given field into an array (for a multi-valued
        // field) 
    }

    return doc;
}

From source file:com.bazaarvoice.jackson.rison.RisonParser.java

/**
 * @return Next token from the stream, if any found, or null
 *   to indicate end-of-input//from   www  . j  a v a 2s  .co  m
 */
@Override
public JsonToken nextToken() throws IOException, JsonParseException {
    _numTypesValid = NR_UNKNOWN;

    if (_currToken == null && _parsingContext.inRoot()) {
        if (isRisonEnabled(Feature.A_RISON)) {
            _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_ARRAY);
        } else if (isRisonEnabled(Feature.O_RISON)) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_OBJECT);
        }
    }

    /* First: field names are special -- we will always tokenize
     * (part of) value along with field name to simplify
     * state handling. If so, can and need to use secondary token:
     */
    if (_currToken == JsonToken.FIELD_NAME) {
        return _nextAfterName();
    }
    if (_tokenIncomplete) {
        _skipString(); // only strings can be partial
    }
    int i = _nextChOrEnd();
    if (i < 0) { // end-of-input
        /* 19-Feb-2009, tatu: Should actually close/release things
         *    like input source, symbol table and recyclable buffers now.
         */
        close();
        if (_parsingContext.getParent().inRoot()) {
            if (isRisonEnabled(Feature.A_RISON) && _parsingContext.inArray()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_ARRAY);
            }
            if (isRisonEnabled(Feature.O_RISON) && _parsingContext.inObject()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_OBJECT);
            }
        }
        _handleEOF();
        return (_currToken = null);
    }

    /* First, need to ensure we know the starting location of token
     * after skipping leading white space
     */
    _tokenInputTotal = _currInputProcessed + _inputPtr - 1;
    _tokenInputRow = _currInputRow;
    _tokenInputCol = _inputPtr - _currInputRowStart - 1;

    // finally: clear any data retained so far
    _binaryValue = null;

    // Closing scope?
    if (i == ')') {
        if (_parsingContext.inArray()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_ARRAY);
        }
        if (_parsingContext.inObject()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_OBJECT);
        }
        _reportMismatchedEndMarker(i, ')');
    }

    // Nope: do we then expect a comma?
    if (_parsingContext.expectComma()) {
        if (i != INT_COMMA) {
            _reportUnexpectedChar(i,
                    "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries");
        }
        i = _nextCh();
    }

    /* And should we now have a name? Always true for
     * Object contexts, since the intermediate 'expect-value'
     * state is never retained.
     */
    boolean inObject = _parsingContext.inObject();
    if (inObject) {
        // First, field name itself:
        String name;
        if (i != INT_APOSTROPHE) {
            name = _parseUnquotedFieldName(i);
        } else {
            name = _parseFieldName(i);
        }
        _parsingContext.setCurrentName(name);
        _currToken = JsonToken.FIELD_NAME;
        i = _nextCh();
        if (i != INT_COLON) {
            _reportUnexpectedChar(i, "was expecting a colon to separate field name and value");
        }
        i = _nextCh();
    }

    // Ok: we must have a value... what is it?

    JsonToken t;

    switch (i) {
    case INT_APOSTROPHE:
        _tokenIncomplete = true;
        t = JsonToken.VALUE_STRING;
        break;
    case '(':
        if (!inObject) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
        }
        t = JsonToken.START_OBJECT;
        break;
    case ')':
        // Error: ')' is not valid at this point; valid closers have
        // been handled earlier
        _reportUnexpectedChar(i, "expected a value");

    case INT_MINUS:
        /* Should we have separate handling for plus? Although
        * it is not allowed per se, it may be erroneously used,
        * and could be indicate by a more specific error message.
        */
    case INT_0:
    case INT_1:
    case INT_2:
    case INT_3:
    case INT_4:
    case INT_5:
    case INT_6:
    case INT_7:
    case INT_8:
    case INT_9:
        t = parseNumberText(i);
        break;

    case '!':
        i = _nextCh();
        switch (i) {
        case '(':
            if (!inObject) {
                _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            }
            t = JsonToken.START_ARRAY;
            break;
        case INT_t:
            t = JsonToken.VALUE_TRUE;
            break;
        case INT_f:
            t = JsonToken.VALUE_FALSE;
            break;
        case INT_n:
            t = JsonToken.VALUE_NULL;
            break;
        default:
            t = _handleUnexpectedValue(i);
            break;
        }
        break;
    default:
        if (IdentifierUtils.isIdStartLenient(i)) {
            t = JsonToken.VALUE_STRING;
            _inputPtr--; // push back the first char
            _parseUnquotedString();
        } else {
            t = _handleUnexpectedValue(i);
        }
        break;
    }

    if (inObject) {
        _nextToken = t;
        return _currToken;
    }
    _currToken = t;
    return t;
}

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public void importQnaContent(final JsonParser jsonParser, final Resource resource,
        final ResourceResolver resolver) throws ServletException, IOException {
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken(); // advance to first key in the object - should be the id value of the old post
        while (jsonParser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
            extractTopic(jsonParser, resource, resolver, qnaForumOperations);
            jsonParser.nextToken(); // get the next token - presumably a field name for the next post
        }/*from   w ww. j av a  2 s.c  o  m*/
        jsonParser.nextToken(); // skip end token
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

/**
 * Checks if the parser returns a textual representation of arbitrary
 * tokens. See issue #23./*from  w  w w .  j  a  v  a  2s  . c om*/
 * @throws Exception if something went wrong
 */
@Test
public void parseAsText() throws Exception {
    BSONObject o = new BasicBSONObject();
    o.put("Float", 5.0f);
    o.put("Int32", 1234);
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    BsonParser dec = fac.createParser(bais);

    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Float", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_FLOAT, dec.nextToken());
    assertEquals(5.0f, dec.getFloatValue(), 0.00001);
    assertEquals("5.0", dec.getText());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Int32", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_INT, dec.nextToken());
    assertEquals(1234, dec.getIntValue());
    assertEquals("1234", dec.getText());

    assertEquals(JsonToken.END_OBJECT, dec.nextToken());
}