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

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

Introduction

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

Prototype

JsonToken START_OBJECT

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

Click Source Link

Document

START_OBJECT is returned when encountering '{' which signals starting of an Object value.

Usage

From source file:com.netflix.hollow.jsonadapter.discover.HollowJsonAdapterSchemaDiscoverer.java

private void discoverSubMapSchemas(JsonParser parser, HollowDiscoveredSchema objectSchema) throws IOException {
    JsonToken token = parser.nextToken();
    if (isDebug)//from w  ww.  java 2  s.  c  o m
        System.out.println(
                "discoverSubMapSchemas[START]: token=" + token + ", fieldname=" + parser.getCurrentName());

    while (token != JsonToken.END_OBJECT) {
        if (isDebug)
            System.out.println(
                    "discoverSubMapSchemas[LOOP]: token=" + token + ", fieldname=" + parser.getCurrentName());
        if (token != JsonToken.FIELD_NAME) {
            if (token == JsonToken.START_OBJECT) {
                if (isDebug)
                    System.out.println("discoverSubMapSchemas[LOOP] discoverSchemas: token=" + token
                            + ", fieldname=" + parser.getCurrentName());
                discoverSchemas(parser, objectSchema);
            } else {
                if (isDebug)
                    System.out.println("discoverSubMapSchemas[LOOP] discoverSchemaField: token=" + token
                            + ", fieldname=" + parser.getCurrentName());
                discoverSchemaField(parser, token, "value", objectSchema);
            }
        }
        token = parser.nextToken();
    }

    if (isDebug)
        System.out.println("discoverSubMapSchemas[END]: token=" + token);
}

From source file:com.sdl.odata.renderer.json.writer.JsonPropertyWriterTest.java

private List<Object> getJsonArray(JsonParser jsonParser) throws IOException {
    List<Object> objects = new ArrayList<>();
    while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) {
            Map<String, String> jsonObject = getJsonObject(jsonParser);
            objects.add(jsonObject);//w ww.  j  a  v a  2  s .c  om
        } else {
            objects.add(jsonParser.getText());
        }
    }
    return objects;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private ContentValues parseObject(JsonParser parser, SQLiteDatabase tempDb, String parentId, int seq)
        throws JsonParseException, IOException {
    // TODO : Grab id of root topic here, and store it in shared prefs, in case it ever
    //        changes. Currently we assume "root" and a change would be catastrophic.
    ContentValues result = new ContentValues();
    ChildArrayResults childResults = null;
    boolean badKind = false;

    result.put("parentTopic_id", parentId);
    result.put("seq", seq);

    while (parser.nextValue() != JsonToken.END_OBJECT) {

        // Allows us to burn through the rest of the object once we discover it's an exercise or something else we don't care about.
        if (badKind)
            continue;

        String fieldName = parser.getCurrentName();

        // Keys present will determine object type.
        if (stringFields.contains(fieldName)) {
            // Use getValueAsString over getText; getText returns "null" while getValueAsString returns null.
            String value = parser.getValueAsString();
            result.put(fieldName, value);

            if ("id".equals(fieldName)) {
                if (childResults != null) {
                    addParentIdToChildren(tempDb, childResults, value);
                }/*w w  w .j  a  v a  2s  . c  o m*/
            }
        } else if (intFields.contains(fieldName)) {
            result.put(fieldName, parser.getIntValue());
        } else if (booleanFields.contains(fieldName)) {
            result.put(fieldName, parser.getBooleanValue());
        } else if ("children".equals(fieldName)) {
            childResults = parseChildArray(parser, tempDb,
                    result.containsKey("id") ? result.getAsString("id") : null);
            result.put("video_count", childResults.videoCount);
            result.put("child_kind", childResults.childKind);
            result.put("thumb_id", childResults.thumbId);
        } else if ("download_urls".equals(fieldName)) {
            parseDownloadUrls(parser, result);
        } else if (null == fieldName) {
            // Noop. Just in case.
        } else {
            JsonToken next = parser.getCurrentToken();
            if (next == JsonToken.START_OBJECT || next == JsonToken.START_ARRAY) {
                // Skip this object or array, leaving us pointing at the matching end_object / end_array token.
                parser.skipChildren();
            }
        }
    }

    // Ignore types we don't need.
    if (badKind) {
        return null;
    }

    // Having parsed this whole object, we can insert it.
    if (result.containsKey("kind")) {
        String kind = result.getAsString("kind");
        if ("Topic".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("_id", result.getAsString("id"));
                result.remove("id");
            }
            if (result.containsKey("child_kind")) {
                String child_kind = result.getAsString("child_kind");
                if ("Topic".equals(child_kind) || "Video".equals(child_kind)) {
                    insertTopic(tempDb, result);
                }
            }
        } else if ("Video".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("video_id", result.getAsString("id"));
                result.remove("id");
            }
            insertTopicVideo(tempDb, result);
            insertVideo(tempDb, result);
        }
    }

    return result;
}

From source file:io.syndesis.jsondb.impl.SqlJsonDB.java

@Override
public void update(String path, InputStream is) {
    ArrayList<String> updatePaths = new ArrayList<>();
    withTransaction(dbi -> {//www .j av a  2s . c o  m
        try {
            BatchManager mb = new BatchManager(dbi);

            try (JsonParser jp = new JsonFactory().createParser(is)) {
                JsonToken nextToken = jp.nextToken();
                if (nextToken != JsonToken.START_OBJECT) {
                    throw new JsonParseException(jp, "Update did not contain a json object");
                }

                while (true) {

                    nextToken = jp.nextToken();
                    if (nextToken == JsonToken.END_OBJECT) {
                        break;
                    }
                    if (nextToken != JsonToken.FIELD_NAME) {
                        throw new JsonParseException(jp, "Expected a field name");
                    }

                    String key = Strings.suffix(path, "/") + jp.getCurrentName();
                    updatePaths.add(key);
                    String baseDBPath = JsonRecordSupport.convertToDBPath(key);
                    mb.deleteRecordsForSet(baseDBPath);

                    try {
                        JsonRecordSupport.jsonStreamToRecords(jp, baseDBPath, mb.createSetConsumer());
                    } catch (IOException e) {
                        throw new JsonDBException(e);
                    }
                }

                nextToken = jp.nextToken();
                if (nextToken != null) {
                    throw new JsonParseException(jp, "Document did not terminate as expected.");
                }
                mb.flush();
            }
        } catch (IOException e) {
            throw new JsonDBException(e);
        }

    });
    if (bus != null) {
        for (String updatePath : updatePaths) {
            bus.broadcast("jsondb-updated", Strings.prefix(Strings.trimSuffix(updatePath, "/"), "/"));
        }
    }
}

From source file:bamboo.trove.common.BaseWarcDomainManager.java

private void parseJson(WarcProgressManager warc, InputStream in) throws IOException {
    Timer.Context ctx = bambooParseTimer.time();
    JsonParser json = createParser(in);/*from  www .ja  va2s. c o  m*/
    JsonToken token = json.nextToken();
    if (token == null) {
        ctx.stop();
        throw new IllegalArgumentException("No JSON data found in response");
    }
    if (!JsonToken.START_ARRAY.equals(token)) {
        ctx.stop();
        throw new IllegalArgumentException("JSON response is not an array");
    }

    try {
        long warcSize = 0;
        while (json.nextToken() == JsonToken.START_OBJECT) {
            Document d = objectMapper.readValue(json, Document.class);
            warcSize += d.getContentLength();
            // Track it by batch
            IndexerDocument doc = warc.add(d);
            // Enqueue it for work
            filterQueue.offer(doc);
        }
        warcDocCountHistogram.update(warc.size());
        warcSizeHistogram.update(warcSize);
        warc.setBatchBytes(warcSize);

    } finally {
        ctx.stop();
    }
}

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

/**
 * Tests reading an embedded document through
 * {@link BsonParser#readValueAsTree()}. Refers issue #9
 * @throws Exception if something went wrong
 * @author audistard/*from ww w .  j  a  v  a2 s . c  om*/
 */
@Test
public void parseEmbeddedDocumentAsTree() throws Exception {
    BSONObject o2 = new BasicBSONObject();
    o2.put("Int64", 10L);

    BSONObject o3 = new BasicBSONObject();
    o3.put("Int64", 11L);

    BSONObject o1 = new BasicBSONObject();
    o1.put("Obj2", o2);
    o1.put("Obj3", o3);

    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o1);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    fac.setCodec(mapper);

    BsonParser dec = fac.createParser(bais);

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

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj2", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());
    JsonNode obj2 = dec.readValueAsTree();
    assertEquals(1, obj2.size());
    assertNotNull(obj2.get("Int64"));
    assertEquals(10L, obj2.get("Int64").longValue());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj3", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Int64", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_INT, dec.nextToken());
    assertEquals(11L, dec.getLongValue());

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

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

From source file:io.pdef.json.JsonJacksonFormat.java

private Map<String, Object> readMap(final JsonParser parser) throws IOException {
    JsonToken current = parser.getCurrentToken();
    if (current != JsonToken.START_OBJECT) {
        throw new JsonFormatException("Bad JSON string, failed to read an object");
    }//from   www .  j a va2 s  . c o  m

    Map<String, Object> map = new LinkedHashMap<String, Object>();
    while (true) {
        JsonToken next = parser.nextToken();
        if (next == null) {
            throw new JsonFormatException("End of file");
        } else if (next == JsonToken.END_OBJECT) {
            break;
        } else if (next != JsonToken.FIELD_NAME) {
            throw new JsonFormatException("Failed to read a field name from " + next);
        }

        String field = parser.getCurrentName();
        parser.nextToken();
        Object value = read(parser);
        map.put(field, value);
    }

    return map;
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse session context object/*from w  w w.  j  av  a  2s .  c o  m*/
 *
 * @param userIdentity the {@link com.amazonaws.services.cloudtrail.processinglibrary.model.internal.UserIdentity}
 * @throws IOException
 * @throws JsonParseException
 */
private void parseSessionContext(UserIdentity userIdentity) throws IOException {
    if (this.jsonParser.nextToken() != JsonToken.START_OBJECT) {
        throw new JsonParseException("Not a SessionContext object", this.jsonParser.getCurrentLocation());
    }

    SessionContext sessionContext = new SessionContext();

    while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = this.jsonParser.getCurrentName();

        switch (key) {
        case "attributes":
            sessionContext.add(CloudTrailEventField.attributes.name(), this.parseAttributes());
            break;
        case "sessionIssuer":
            sessionContext.add(CloudTrailEventField.sessionIssuer.name(),
                    this.parseSessionIssuer(sessionContext));
            break;
        case "webIdFederationData":
            sessionContext.add(CloudTrailEventField.webIdFederationData.name(),
                    this.parseWebIdentitySessionContext(sessionContext));
            break;
        default:
            sessionContext.add(key, this.parseDefaultValue(key));
            break;
        }
    }

    userIdentity.add(CloudTrailEventField.sessionContext.name(), sessionContext);

}

From source file:bamboo.trove.full.FullReindexWarcManager.java

private LinkedList<ToIndex> getNextBatch() throws IOException {
    long startOfNextBatch = endOfBatchId + 1;
    URL url = new URL(bambooCollectionsUrl + "?start=" + startOfNextBatch + "&rows=" + bambooBatchSize);
    log.info("Contacting Bamboo for more IDs. start={}, rows={}", startOfNextBatch, bambooBatchSize);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream in = new BufferedInputStream(connection.getInputStream());

    ObjectMapper om = getObjectMapper();
    JsonParser json = createParser(in);//from  w w w  .ja v a  2  s.c o  m
    JsonToken token = json.nextToken();

    if (token == null) {
        throw new IllegalArgumentException("No JSON data found in response");
    }
    if (!JsonToken.START_ARRAY.equals(token)) {
        throw new IllegalArgumentException("JSON response is not an array");
    }

    LinkedList<ToIndex> result = new LinkedList<>();
    while (json.nextToken() == JsonToken.START_OBJECT) {
        result.add(new ToIndex(om.readValue(json, WarcToIndex.class)));
    }
    return result;
}

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

/**
 * Private routine to deserialize a JSON containing attachment data. This is
 * done manually to give more freedom regarding data returned by the
 * webservice.//from w w w.j  a  va  2  s . com
 *
 * @param parser the JSONParser containing JSONData.
 * @param attachmentDB the attachments stored in the Toolkit
 * @return List containing attachments
 *
 * @throws JsonParseException
 * @throws IOException
 */
private List<Attachment> deserializeAttachmentList(JsonParser parser, Map<String, Attachment> attachmentDB)
        throws JsonParseException, IOException {
    List<Attachment> attachments = new ArrayList<Attachment>();
    Attachment currentAttachment = null;

    while (!JsonToken.END_ARRAY.equals(parser.nextToken())) {

        String fieldName = parser.getCurrentName();
        JsonToken token = parser.getCurrentToken();

        if (JsonToken.START_OBJECT.equals(token)) {
            currentAttachment = new Attachment();
        } else if (JsonToken.END_OBJECT.equals(token)) {
            currentAttachment.setCapGroupSMILES(
                    attachmentDB.get(currentAttachment.getAlternateId()).getCapGroupSMILES());
            attachments.add(currentAttachment);
        }

        if (fieldName != null) {
            switch (fieldName) {
            case "id":
                parser.nextToken();
                currentAttachment.setId(Integer.parseInt(parser.getText()));
                break;
            case "alternateId":
                parser.nextToken();
                currentAttachment.setAlternateId(parser.getText());
                break;
            case "label":
                parser.nextToken();
                currentAttachment.setLabel(parser.getText());
                break;
            case "capGroupName":
                parser.nextToken();
                currentAttachment.setCapGroupName(parser.getText());
                break;
            case "capGroupSMILES":
                parser.nextToken();
                currentAttachment.setCapGroupSMILES(parser.getText());
                break;
            default:
                break;
            }
        }

    }

    return attachments;
}