Example usage for com.fasterxml.jackson.core JsonParser nextToken

List of usage examples for com.fasterxml.jackson.core JsonParser nextToken

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser nextToken.

Prototype

public abstract JsonToken nextToken() throws IOException, JsonParseException;

Source Link

Document

Main iteration method, which will advance stream enough to determine type of the next token, if any.

Usage

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

/**
 * Begins parsing a JSON stream into a tree structure. The JsonValue object
 * created contains the value at the root of the tree.
 * //  w ww  .  j  a va  2 s. co  m
 * This constructor will block until the first JSON token is received. To
 * continue building the tree, the "build" method (inherited from
 * JsonBuffered) must be called in another thread.
 * 
 * @param jp
 *         The incoming JSON stream
 * @throws java.io.IOException
 */
public JsonValue(final JsonParser jp) throws IOException {
    this(jp, jp.nextToken());
}

From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java

@Nullable
public Object _deserializeTypedFromObject(ObjectNode objectNode, ObjectCodec objectCodec,
        DeserializationContext ctxt) throws IOException {
    if (objectNode.hasNonNull(_typePropertyName)) {
        return _deserializeObjectFromProperty(objectNode, objectCodec, ctxt);
    }/*from  ww w  . jav a2 s. c om*/
    String singleKeyName = getSingleKeyIfPresent(objectNode);
    if (singleKeyName != null) {
        Object bean = _deserializeObjectFromSingleKey(objectNode, singleKeyName, objectCodec, ctxt);
        if (bean != null) {
            return bean;
        }
    }
    Object bean = _deserializeObjectFromInlinedType(objectNode, objectCodec, ctxt);
    if (bean != null) {
        return bean;
    }
    if (idRes.isValidTypeId("_default")) {
        ConfigObject aliasDefaults = pluginMap.aliasDefaults("_default");
        JsonDeserializer<Object> deser = _findDeserializer(ctxt, "_default");
        boolean unwrapPrimary = handleDefaultsAndImplicitPrimary(objectNode, aliasDefaults, deser, ctxt);
        try {
            JsonParser treeParser = objectCodec.treeAsTokens(objectNode);
            treeParser.nextToken();
            bean = deser.deserialize(treeParser, ctxt);
        } catch (IOException cause) {
            if (unwrapPrimary) {
                throw Jackson.maybeUnwrapPath((String) aliasDefaults.get("_primary").unwrapped(), cause);
            } else {
                throw cause;
            }
        }
    }
    return bean;
}

From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java

@Override
public Object deserializeTypedFromAny(JsonParser jp, DeserializationContext ctxt) throws IOException {
    // a jackson thing we might as well include
    if (jp.canReadTypeId()) {
        Object typeId = jp.getTypeId();
        if (typeId != null) {
            return _deserializeWithNativeTypeId(jp, ctxt, typeId);
        }/*  w w  w. ja  v  a2s.co m*/
    }
    // can use this to approximate error location if a sub-method throws an exception
    JsonLocation currentLocation = jp.getTokenLocation();
    JsonNode jsonNode;
    // empty objects can appear with END_OBJECT. that has special handling lots of places, but not in readTree
    if (jp.getCurrentToken() == JsonToken.END_OBJECT) {
        jsonNode = ctxt.getNodeFactory().objectNode();
    } else {
        jsonNode = jp.readValueAsTree();
    }
    ObjectCodec objectCodec = jp.getCodec();

    try {
        Object bean = null;
        // _array handler
        if (jsonNode.isArray()) {
            bean = _deserializeTypedFromArray((ArrayNode) jsonNode, objectCodec, ctxt);
            // object handler
        } else if (jsonNode.isObject()) {
            bean = _deserializeTypedFromObject((ObjectNode) jsonNode, objectCodec, ctxt);
        }
        if (bean != null) {
            return bean;
        } else {
            // Jackson 2.6+ throws NPE on null typeId parameter (underlying Map changed from HashMap
            // to ConcurrentHashMap), so use empty string instead of null
            JsonDeserializer<Object> deser = _findDeserializer(ctxt, "");
            JsonParser treeParser = jp.getCodec().treeAsTokens(jsonNode);
            treeParser.nextToken();
            return deser.deserialize(treeParser, ctxt);
        }
    } catch (JsonMappingException ex) {
        throw Jackson.maybeImproveLocation(currentLocation, ex);
    }
}

From source file:name.gumartinm.weather.information.parser.JPOSCurrentParser.java

private void getCurrentWeatherDataObjects(final Current currentWeatherData, final JsonParser jParser,
        final String fieldname) throws JsonParseException, IOException {
    if ("coord".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("lon".equals(namefield)) {
                currentWeatherData.getCoord().setLon(jParser.getDoubleValue());
            }//from w  ww.  j  a  v a2 s.co m
            if ("lat".equals(namefield)) {
                currentWeatherData.getCoord().setLat(jParser.getDoubleValue());
            }
        }
    }
    if ("sys".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("message".equals(namefield)) {
                currentWeatherData.getSys().setMessage(jParser.getDoubleValue());
            }
            if ("country".equals(namefield)) {
                currentWeatherData.getSys().setCountry(jParser.getValueAsString());
            }
            if ("sunrise".equals(namefield)) {
                currentWeatherData.getSys().setSunrise(jParser.getValueAsLong());
            }
            if ("sunset".equals(namefield)) {
                currentWeatherData.getSys().setSunset(jParser.getValueAsLong());
            }
        }
    }
    if ("weather".equals(fieldname)) {
        final Weather weather = new Weather();
        currentWeatherData.getWeather().add(weather);
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("id".equals(namefield)) {
                weather.setId(jParser.getIntValue());
            }
            if ("main".equals(namefield)) {
                weather.setMain(jParser.getText());
            }
            if ("description".equals(namefield)) {
                weather.setDescription(jParser.getText());
            }
            if ("icon".equals(namefield)) {
                weather.setIcon(jParser.getText());
            }

        }
    }
    if ("base".equals(fieldname)) {
        currentWeatherData.setBase(jParser.getText());
    }
    if ("main".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("temp".equals(namefield)) {
                currentWeatherData.getMain().setTemp(jParser.getDoubleValue());
            }
            if ("temp_min".equals(namefield)) {
                currentWeatherData.getMain().setTemp_min(jParser.getDoubleValue());
            }
            if ("temp_max".equals(namefield)) {
                currentWeatherData.getMain().setTemp_max(jParser.getDoubleValue());
            }
            if ("pressure".equals(namefield)) {
                currentWeatherData.getMain().setPressure(jParser.getDoubleValue());
            }
            if ("sea_level".equals(namefield)) {
                currentWeatherData.getMain().setSea_level(jParser.getDoubleValue());
            }
            if ("grnd_level".equals(namefield)) {
                currentWeatherData.getMain().setGrnd_level(jParser.getDoubleValue());
            }
            if ("humidity".equals(namefield)) {
                currentWeatherData.getMain().setHumidity(jParser.getDoubleValue());
            }
        }
    }
    if ("wind".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("speed".equals(namefield)) {
                currentWeatherData.getWind().setSpeed(jParser.getDoubleValue());
            }
            if ("deg".equals(namefield)) {
                currentWeatherData.getWind().setDeg(jParser.getDoubleValue());
            }
        }
    }
    if ("clouds".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("all".equals(namefield)) {
                currentWeatherData.getClouds().setAll(jParser.getDoubleValue());
            }
        }
    }
    if ("dt".equals(fieldname)) {
        currentWeatherData.setDt(jParser.getLongValue());
    }
    if ("rain".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("3h".equals(namefield)) {
                currentWeatherData.getRain().set3h(jParser.getDoubleValue());
            }
        }
    }
    if ("snow".equals(fieldname)) {
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            final String namefield = jParser.getCurrentName();
            jParser.nextToken(); // move to value
            if ("3h".equals(namefield)) {
                currentWeatherData.getSnow().set3h(jParser.getDoubleValue());
            }
        }
    }
    if ("id".equals(fieldname)) {
        currentWeatherData.setId(jParser.getLongValue());
    }
    if ("name".equals(fieldname)) {
        currentWeatherData.setName(jParser.getText());
    }
    if ("cod".equals(fieldname)) {
        currentWeatherData.setCod(jParser.getIntValue());
    }
}

From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java

@Nullable
private Object _deserializeObjectFromInlinedType(ObjectNode objectNode, ObjectCodec objectCodec,
        DeserializationContext ctxt) throws IOException {
    String matched = null;/*from w ww. ja  va  2  s.c o m*/
    for (String alias : pluginMap.inlinedAliases()) {
        if (objectNode.get(alias) != null) {
            if (matched != null) {
                String message = String.format(
                        "no type specified, more than one key, and both %s and %s match for inlined types.",
                        matched, alias);
                JsonMappingException exception = ctxt.instantiationException(_baseType.getRawClass(), message);
                exception.prependPath(_baseType, matched);
                throw exception;
            }
            matched = alias;
        }
    }
    if (matched != null) {
        ConfigObject aliasDefaults = pluginMap.aliasDefaults(matched);
        JsonNode configValue = objectNode.get(matched);
        String primaryField = (String) aliasDefaults.get("_primary").unwrapped();
        objectNode.remove(matched);
        Jackson.setAt(objectNode, configValue, primaryField);
        Jackson.merge(objectNode, Jackson.configConverter(aliasDefaults));
        if (_typeIdVisible) {
            objectNode.put(_typePropertyName, matched);
        }
        try {
            JsonDeserializer<Object> deser = _findDeserializer(ctxt, matched);
            JsonParser treeParser = objectCodec.treeAsTokens(objectNode);
            treeParser.nextToken();
            return deser.deserialize(treeParser, ctxt);
        } catch (IOException cause) {
            IOException unwrapped = Jackson.maybeUnwrapPath(primaryField, cause);
            if (unwrapped != cause) {
                throw wrapWithPath(unwrapped, idRes.typeFromId(ctxt, matched), matched);
            } else {
                throw unwrapped;
            }
        }
    } else {
        return null;
    }
}

From source file:com.cedarsoft.couchdb.io.RawCouchDocSerializer.java

@Nonnull
public RawCouchDoc deserialize(@Nonnull JsonParser parser) throws IOException {
    JacksonParserWrapper parserWrapper = new JacksonParserWrapper(parser);
    parserWrapper.nextToken(JsonToken.START_OBJECT);

    parserWrapper.nextFieldValue(PROPERTY_ID);
    String id = parser.getText();

    parserWrapper.nextFieldValue(PROPERTY_REV);
    String rev = parser.getText();

    parser.nextToken();

    parserWrapper.ensureObjectClosed();// w  ww.ja  v a 2s .  c  om
    return new RawCouchDoc(new DocId(id), new Revision(rev));
}

From source file:org.helm.notation2.wsadapter.NucleotideWSLoader.java

/**
 * Private routine to deserialize nucleotide Store JSON. This is done manually to give more freedom regarding data
 * returned by the webservice.//w  w  w.j a  v a  2  s  . com
 * 
 * @param parser the JSONParser containing JSONData.
 * @return Map containing nucleotides
 * 
 * @throws JsonParseException
 * @throws IOException
 */
private Map<String, String> deserializeNucleotideStore(JsonParser parser)
        throws JsonParseException, IOException {
    Map<String, String> nucleotides = new HashMap<String, String>();
    String currentNucleotideSymbol = "";
    String currentNucleotideNotation = "";
    boolean foundSymbol = false;
    boolean foundNotation = false;

    parser.nextToken();
    while (parser.hasCurrentToken()) {
        String fieldName = parser.getCurrentName();

        if (fieldName != null) {
            switch (fieldName) {
            case "symbol":
                parser.nextToken();
                currentNucleotideSymbol = parser.getText();
                foundSymbol = true;
                break;
            case "notation":
                parser.nextToken();
                currentNucleotideNotation = parser.getText();
                foundNotation = true;
                break;
            default:
                break;
            }

            if (foundSymbol && foundNotation) {
                nucleotides.put(currentNucleotideSymbol, currentNucleotideNotation);
                foundNotation = false;
                foundSymbol = false;
            }
        }
        parser.nextToken();
    }

    return nucleotides;
}

From source file:org.oscim.tiling.source.geojson.GeoJsonTileDecoder.java

private void parseCoordinate(JsonParser jp) throws JsonParseException, IOException {
    int pos = 0;//w w w. j a  va2s  .  c  o m
    double x = 0, y = 0; //, z = 0;

    for (JsonToken t; (t = jp.nextToken()) != null;) {
        if (t == VALUE_NUMBER_FLOAT || t == VALUE_NUMBER_INT) {

            // avoid String allocation (by getDouble...)
            char[] val = jp.getTextCharacters();
            int offset = jp.getTextOffset();
            int length = jp.getTextLength();
            double c = ArrayUtils.parseNumber(val, offset, offset + length);

            if (pos == 0)
                x = c;
            if (pos == 1)
                y = c;
            //if (pos == 2)
            //z = c;

            pos++;
            continue;
        }

        if (t == END_ARRAY)
            break;
    }

    mMapElement.addPoint((float) ((longitudeToX(x) - mTileX) * mTileScale),
            (float) ((latitudeToY(y) - mTileY) * mTileScale));

}

From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java

@Nullable
private Object _deserializeObjectFromSingleKey(ObjectNode objectNode, String singleKeyName,
        ObjectCodec objectCodec, DeserializationContext ctxt) throws IOException {
    if (idRes.isValidTypeId(singleKeyName)) {
        ConfigObject aliasDefaults = pluginMap.aliasDefaults(singleKeyName);
        String primaryField;/* w  w  w .  j  a  v  a  2 s .c o  m*/
        if (aliasDefaults.containsKey("_primary")) {
            primaryField = (String) aliasDefaults.get("_primary").unwrapped();
        } else {
            primaryField = null;
        }
        boolean unwrapPrimary = false;
        try {
            JsonNode singleKeyValue = objectNode.get(singleKeyName);
            JsonDeserializer<Object> deser = _findDeserializer(ctxt, singleKeyName);
            if (!singleKeyValue.isObject()) {
                // if value is not an object, try supporting _primary syntax to derive one
                if (primaryField != null) {
                    ObjectNode singleKeyObject = (ObjectNode) objectCodec.createObjectNode();
                    Jackson.setAt(singleKeyObject, singleKeyValue, primaryField);
                    Jackson.merge(singleKeyObject, Jackson.configConverter(aliasDefaults));
                    singleKeyValue = singleKeyObject;
                    unwrapPrimary = true;
                } // else let the downstream serializer try to handle it or complain
            } else {
                ObjectNode singleKeyObject = (ObjectNode) singleKeyValue;
                unwrapPrimary = handleDefaultsAndImplicitPrimary(singleKeyObject, aliasDefaults, deser, ctxt);
            }
            if (_typeIdVisible && singleKeyValue.isObject()) {
                ((ObjectNode) singleKeyValue).put(_typePropertyName, singleKeyName);
            }
            JsonParser treeParser = objectCodec.treeAsTokens(singleKeyValue);
            treeParser.nextToken();
            return deser.deserialize(treeParser, ctxt);
        } catch (IOException cause) {
            if (unwrapPrimary) {
                cause = Jackson.maybeUnwrapPath(primaryField, cause);
            }
            throw wrapWithPath(cause, idRes.typeFromId(ctxt, singleKeyName), singleKeyName);
        } catch (Throwable cause) {
            throw wrapWithPath(cause, idRes.typeFromId(ctxt, singleKeyName), singleKeyName);
        }
    }
    return null;
}

From source file:com.basho.riak.client.raw.http.NamedJSFunctionDeserializer.java

@Override
public NamedJSFunction deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken token = jp.getCurrentToken();

    if (JsonToken.START_OBJECT.equals(token)) {

        String name = null;//from  ww  w .ja v a 2 s  .  c  o  m

        while (!JsonToken.END_OBJECT.equals(token)) {
            String field = jp.getCurrentName();

            if (Constants.FL_SCHEMA_FUN_NAME.equals(field)) {
                jp.nextToken();
                name = jp.getText();
            }
            token = jp.nextToken();
        }
        if (name != null) {
            return new NamedJSFunction(name);
        } else {
            return null;
        }
    }
    throw ctxt.mappingException(NamedJSFunction.class);
}