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

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

Introduction

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

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

From source file:com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer.java

@Override
public Application deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String name = null;//from   w  ww .  ja  v a2 s  . c  o m
    List<InstanceInfo> instances = new ArrayList<>();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("name".equals(fieldName)) {
            name = jp.getValueAsString();
        } else if ("instance".equals(fieldName)) {
            instances.add(jp.readValueAs(InstanceInfo.class));
        } else {
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new Application(name, instances);
}

From source file:eu.trentorise.opendata.semtext.jackson.MetadataDeserializer.java

@Override
public Map<String, Object> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

    ImmutableMap.Builder<String, Object> retb = ImmutableMap.builder();

    while (jp.nextToken() != JsonToken.END_OBJECT) {

        String namespace = jp.getCurrentName();
        // current token is "name",
        // move to next, which is "name"'s value
        jp.nextToken();//from  w ww .j  a  va2  s .c  o  m

        ImmutableSet<String> namespaces = SemTextModule.getMetadataNamespaces(hasMetadataClass);
        if (namespaces.contains(namespace)) {
            TypeReference typeRef = SemTextModule.getMetadataTypeReference(hasMetadataClass, namespace);

            Object metadata;

            try {
                metadata = jp.readValueAs(typeRef);
            } catch (Exception ex) {
                throw new SemTextMetadataException("Jackson error while deserializing metadata - ",
                        hasMetadataClass, namespace, typeRef, ex);
            }

            if (metadata == null) {
                throw new SemTextMetadataException("Found null metadata while deserializing!", hasMetadataClass,
                        namespace, typeRef);
            }

            retb.put(namespace, metadata);
        } else {
            throw new SemTextMetadataException(
                    "Found metadata under not registered namespace while deserializing!", hasMetadataClass,
                    namespace, null);
        }
    }

    return retb.build();
}

From source file:org.apache.ode.jacob.soup.jackson.ChannelProxyDeserializer.java

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

    String type = null;/*from  w ww .  j a  v a2  s.  c o  m*/
    int id = -1;
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
            // if we're not already on the field, advance by one.
            jp.nextToken();
        }
        if ("channelType".equals(fieldname)) {
            type = jp.getText();
        } else if ("channelId".equals(fieldname)) {
            id = jp.getIntValue();
        }
    }

    if (type == null) {
        throw ctxt.mappingException(Channel.class);
    }

    if (id < 0) {
        throw ctxt.mappingException(Channel.class);
    }

    try {
        CommChannel cchannel = new CommChannel(ctxt.findClass(type));
        cchannel.setId(id);
        return (Channel) ChannelFactory.createChannel(cchannel, cchannel.getType());

    } catch (ClassNotFoundException e) {
        throw ctxt.instantiationException(Channel.class, e);
    }
}

From source file:com.netflix.aegisthus.tools.AegisthusSerializer.java

public Map<String, Object> deserialize(String data) throws IOException {
    try {/*from  w w  w  .  j  a va2 s .  c o  m*/
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        JsonParser jp = jsonFactory.createJsonParser(data);
        jp.nextToken(); // Object
        jp.nextToken(); // key
        map.put(KEY, new DataByteArray(jp.getCurrentName().getBytes()));
        jp.nextToken(); // object
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String field = jp.getCurrentName();
            if (DELETEDAT.equals(field.toUpperCase())) {
                jp.nextToken();
                map.put(DELETEDAT, jp.getLongValue());
            } else {
                jp.nextToken();
                while (jp.nextToken() != JsonToken.END_ARRAY) {
                    List<Object> cols = new ArrayList<Object>();
                    jp.nextToken();
                    String name = jp.getText();
                    cols.add(name);
                    jp.nextToken();
                    cols.add(new DataByteArray(jp.getText().getBytes()));
                    jp.nextToken();
                    cols.add(jp.getLongValue());
                    if (jp.nextToken() != JsonToken.END_ARRAY) {
                        String status = jp.getText();
                        cols.add(status);
                        if ("e".equals(status)) {
                            jp.nextToken();
                            cols.add(jp.getLongValue());
                            jp.nextToken();
                            cols.add(jp.getLongValue());
                        } else if ("c".equals(status)) {
                            jp.nextToken();
                            cols.add(jp.getLongValue());
                        }
                        jp.nextToken();
                    }
                    map.put(name, cols);
                }
            }
        }

        return map;
    } catch (IOException e) {
        LOG.error(data);
        throw e;
    }
}

From source file:org.o3project.ocnrm.odenos.linklayerizer.LinkLayerizerBoundarySet.java

public Map<String, LinklayerizerBoundary> changeJSONBoundariesToBoundaries(String jsonBoundary, String seqNo) {

    logger.info(seqNo + "\t" + "changeJSONBoundariestoBoundaries Start");

    linklayerizerBoundaryMap = new HashMap<String, LinklayerizerBoundary>();
    try {/*from  w  w w  .  j  a  v a 2s  .com*/
        JsonFactory factory = new JsonFactory();
        JsonParser jp = factory.createParser(jsonBoundary);
        jp.nextToken();
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String mapKey = jp.getCurrentName();
            LinklayerizerBoundary llb = new LinklayerizerBoundary();
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                jp.nextToken();
                if ("boundary_id".equals(fieldname)) {
                    llb.setBoundary_id(jp.getText());
                } else if ("lower_nw".equals(fieldname)) {
                    llb.setLower_nw(jp.getText());
                } else if ("lower_nw_node".equals(fieldname)) {
                    llb.setLower_nw_node(jp.getText());
                } else if ("lower_nw_port".equals(fieldname)) {
                    llb.setLower_nw_port(jp.getText());
                } else if ("upper_nw".equals(fieldname)) {
                    llb.setUpper_nw(jp.getText());
                } else if ("upper_nw_node".equals(fieldname)) {
                    llb.setUpper_nw_node(jp.getText());
                } else if ("upper_nw_port".equals(fieldname)) {
                    llb.setUpper_nw_port(jp.getText());
                } else if ("type".equals(fieldname)) {
                    continue;
                } else {
                    throw new IllegalStateException(seqNo + "\t" + "Unrecognized field '" + fieldname + "'!");
                }
            }
            linklayerizerBoundaryMap.put(mapKey, llb);
        }
        jp.close();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    logger.info(seqNo + "\t" + "changeJSONBoundariestoBoundaries End");
    return linklayerizerBoundaryMap;
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Parse the complex values.//from   ww  w.  j  a  v  a2  s . co  m
 *
 * @param jsonParser the parser
 * @return list of parsed result objects
 * @throws IOException If unable to read input parser
 */
private List<Object> getCollectionValue(JsonParser jsonParser) throws IOException {
    LOG.info("Start parsing {} array", jsonParser.getCurrentName());
    List<Object> list = new ArrayList<>();
    while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) {
            Object embedded = getEmbeddedObject(jsonParser);
            list.add(embedded);
        }
        if (!"}".equals(jsonParser.getText())) {
            list.add(jsonParser.getText());
        } else {
            LOG.info("Array is over.");
        }
    }
    return list;
}

From source file:KV78Tester.java

public void checkStop(JsonParser jp, String line, int userStopOrder) throws JsonParseException, IOException {
    boolean hasTown = false, hasName = false;
    String timingPoint = "";
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String namefield = jp.getCurrentName();
        jp.nextToken();/*w  w w  .jav a  2s . c  om*/
        if ("Town".equals(namefield)) {
            hasTown = true;
        }
        if ("Name".equals(namefield)) {
            hasName = true;
        }
        if ("TimingPointCode".equals(namefield)) {
            timingPoint = jp.getText();
        }
    }
    if (!hasTown && !hasName)
        System.out.println(String.format("Line %s misses townname and stopname for stopnumer %d, TPC %s", line,
                userStopOrder, timingPoint));
    else if (!hasTown)
        System.out.println(String.format("Line %s misses townname for stopnumer %d, TPC %s", line,
                userStopOrder, timingPoint));
    else if (!hasName)
        System.out.println(String.format("Line %s misses stopname for stopnumer %d, TPC %s", line,
                userStopOrder, timingPoint));
}

From source file:org.metis.utils.Utils.java

/**
 * Recursively steps through JSON object and arrays of objects. We support
 * only a single object or an array of objects, where each object represents
 * an entity (e.g., a student, a customer, an account, etc.).
 * /*from   w w  w .  j a  v a 2s  .  c  o  m*/
 * All objects must have the same identical set of keys.
 * 
 * @param jp
 * @param params
 * @throws Exception
 */
private static void parseJson(JsonParser jp, List<Map<String, String>> rows) throws Exception {

    // get the next json token
    JsonToken current = jp.nextToken();

    // base case: return if we've reached end of json stream
    if (current == null) {
        return;
    }

    // all rows must have the identical set of keys!
    Map<String, String> firstRow = null;
    if (!rows.isEmpty()) {
        firstRow = rows.get(0);
    }

    // we only accept objects or arrays of objects
    switch (current) {
    case START_OBJECT:
        HashMap<String, String> row = new HashMap<String, String>();
        while (jp.nextToken() != END_OBJECT) {
            // parser should be on 'key' token
            String key = jp.getCurrentName().toLowerCase();
            // ensure all rows have the identical set of keys!
            if (firstRow != null && firstRow.get(key) == null) {
                String eStr = "parseJson: given list of json objects do " + "not have identical set of keys";
                LOG.error(eStr);
                throw new Exception(eStr);
            }
            // now advance to 'value' token
            jp.nextToken();
            String value = jp.getText();
            row.put(key, value);
        }
        // if row is not null, add it to the rows list
        if (!row.isEmpty()) {
            // ensure all rows have the identical set of keys!
            if (firstRow != null && firstRow.size() != row.size()) {
                String eStr = "parseJson: given list of json objects do "
                        + "not have identical set of keys; number of " + "keys vary";
                LOG.error(eStr);
                throw new Exception(eStr);
            }
            rows.add(row);
        }
        break;
    case START_ARRAY:
    case END_ARRAY:
        break;
    default:
        LOG.error("parseJson: ERROR, json token is neither object nor array");
        throw new Exception("parseJson: ERROR, json token is neither object nor array");
    }

    // go on to the next start-of-array, end-of-array, start-of-object, or
    // end of stream
    parseJson(jp, rows);
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * This method fills odataMap that contains special tags "odata" with key:value When the key token is over, you need
 * to execute nextToken() in order to get value.
 *
 * @param jsonParser the parser// w w  w.ja  va 2s  .  c o m
 * @throws IOException If unable to read input parser
 */
private void processSpecialTags(JsonParser jsonParser) throws IOException {
    LOG.info("@odata tags found - start parsing");
    String key = jsonParser.getCurrentName();
    jsonParser.nextToken();
    String value = jsonParser.getText();
    odataValues.put(key, value);
}

From source file:com.pursuer.reader.easyrss.data.parser.SubscriptionJSONParser.java

public void parse() throws JsonParseException, IOException, IllegalStateException {
    final JsonFactory factory = new JsonFactory();
    final JsonParser parser = factory.createJsonParser(input);
    Subscription sub = new Subscription();
    int level = 0;
    boolean found = false;
    while (parser.nextToken() != null) {
        final String name = parser.getCurrentName();
        switch (parser.getCurrentToken()) {
        case START_OBJECT:
        case START_ARRAY:
            level++;/*w  w  w .  ja  va2 s.c  om*/
            break;
        case END_OBJECT:
        case END_ARRAY:
            level--;
            break;
        case VALUE_STRING:
            if (level == 3) {
                if ("id".equals(name)) {
                    sub.setUid(parser.getText());
                } else if ("htmlUrl".equals(name)) {
                    sub.setUrl(parser.getText());
                } else if ("title".equals(name)) {
                    sub.setTitle(Html.fromHtml(parser.getText()).toString());
                } else if ("sortid".equals(name)) {
                    sub.setSortId(parser.getText());
                } else if ("firstitemmsec".equals(name)) {
                    sub.setFirstItemMsec(Long.valueOf(parser.getText()));
                }
            } else if (level == 5 && "id".equals(name)) {
                sub.addTag(parser.getText());
            }
            break;
        case FIELD_NAME:
            if (level == 1 && "subscriptions".equals(name)) {
                found = true;
            }
            break;
        default:
        }
        if (level == 2) {
            if (sub.getUid() != null && listener != null) {
                listener.onSubscriptionRetrieved(sub);
            }
            sub = new Subscription();
        }
    }
    parser.close();
    if (!found) {
        throw new IllegalStateException("Invalid JSON input");
    }
}