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:io.wcm.caravan.io.jsontransform.source.JacksonStreamSource.java

private JsonElement handleFieldName(String key) throws IOException, JsonParseException {
    JsonToken next = parser.nextToken();
    if (JsonToken.START_OBJECT.equals(next)) {
        return JsonElement.startObject(key);
    } else if (JsonToken.START_ARRAY.equals(next)) {
        return JsonElement.startArray(key);
    } else {/*ww w . j a  va  2s . c  o  m*/
        return JsonElement.value(key, parseValue(next));
    }
}

From source file:io.debezium.document.JacksonReader.java

private Document parseDocument(JsonParser parser, boolean nested) throws IOException {
    // Iterate over the fields in the top-level document ...
    BasicDocument doc = new BasicDocument();
    JsonToken token = null;/*from   w w w. ja va2 s .  c  o  m*/
    if (!nested) {
        // We expect the START_OBJECT token ...
        token = parser.nextToken();
        if (!nested && token != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object, but was " + token);
        }
    }
    String fieldName = null;
    token = parser.nextToken();
    while (token != JsonToken.END_OBJECT) {
        switch (token) {
        case FIELD_NAME:
            fieldName = parser.getCurrentName();
            break;
        case START_OBJECT:
            doc.setDocument(fieldName, parseDocument(parser, true));
            break;
        case START_ARRAY:
            doc.setArray(fieldName, parseArray(parser, true));
            break;
        case VALUE_STRING:
            doc.setString(fieldName, parser.getValueAsString());
            break;
        case VALUE_TRUE:
            doc.setBoolean(fieldName, true);
            break;
        case VALUE_FALSE:
            doc.setBoolean(fieldName, false);
            break;
        case VALUE_NULL:
            doc.setNull(fieldName);
            break;
        case VALUE_NUMBER_FLOAT:
        case VALUE_NUMBER_INT:
            switch (parser.getNumberType()) {
            case FLOAT:
                doc.setNumber(fieldName, parser.getFloatValue());
                break;
            case DOUBLE:
                doc.setNumber(fieldName, parser.getDoubleValue());
                break;
            case BIG_DECIMAL:
                doc.setNumber(fieldName, parser.getDecimalValue());
                break;
            case INT:
                doc.setNumber(fieldName, parser.getIntValue());
                break;
            case LONG:
                doc.setNumber(fieldName, parser.getLongValue());
                break;
            case BIG_INTEGER:
                doc.setNumber(fieldName, parser.getBigIntegerValue());
                break;
            }
            break;
        case VALUE_EMBEDDED_OBJECT:
            // disregard this, since it's an extension ...
            break;
        case NOT_AVAILABLE:
            throw new JsonParseException("Non-blocking parsers are not supported", parser.getCurrentLocation());
        case END_ARRAY:
            throw new JsonParseException("Not expecting an END_ARRAY token", parser.getCurrentLocation());
        case END_OBJECT:
            throw new JsonParseException("Not expecting an END_OBJECT token", parser.getCurrentLocation());
        }
        token = parser.nextToken();
    }
    return doc;
}

From source file:org.hbz.oerworldmap.JsonDecoder.java

@Override
public void process(final Reader reader) {
    STARTED = false;//from w  ww . j  ava  2  s  .co  m
    JsonDecoder.LOG.debug("############################ New");
    // necessary if it is JSONP
    String text;
    try {
        text = CharStreams.toString(reader);
        this.jsonParser = new JsonFactory().createParser(text);
        // find start
        JsonToken currentToken = null;
        try {
            currentToken = this.jsonParser.nextToken();
        } catch (final JsonParseException e) {
            // assuming JSONP :
            final String callbackString = text.substring(0, text.indexOf(JsonDecoder.JSON_START_CHAR) - 1);
            text = text.substring(text.indexOf(JsonDecoder.JSON_START_CHAR), text.length() - 1);
            this.jsonParser = new JsonFactory().createParser(text);
            JsonDecoder.LOG.debug("key=" + JsonDecoder.JSON_CALLBACK + " value=" + callbackString);
            getReceiver().startRecord("");
            STARTED = true;
            JSONP = true;
            getReceiver().literal(JsonDecoder.JSON_CALLBACK, callbackString);
            JsonDecoder.LOG.debug("Text=" + text);
            currentToken = this.jsonParser.nextToken();
        }
        while (JsonToken.START_OBJECT != currentToken) {
            this.jsonParser.nextToken();
        }

        String key = null;
        while (currentToken != null) {
            if (JsonToken.START_OBJECT == currentToken) {
                if (!STARTED) {
                    getReceiver().startRecord("");
                    STARTED = true;
                }
                currentToken = this.jsonParser.nextToken();
                while (currentToken != null) {
                    if (JsonToken.FIELD_NAME == currentToken) {
                        key = this.jsonParser.getCurrentName();
                    }
                    if (JsonToken.START_ARRAY == currentToken) {
                        if (this.JSONP) {
                            currentToken = this.jsonParser.nextToken();
                            currentToken = this.jsonParser.nextToken();
                        } else {
                            currentToken = this.jsonParser.nextToken();
                            // treat objects in arrays as new objects
                            if (JsonToken.START_OBJECT == currentToken) {
                                break;
                            }
                            // values of arrays are submitted with an index
                            // so
                            // you can handle
                            // semantics in the morph
                            int i = 0;
                            while (JsonToken.END_ARRAY != currentToken) {
                                final String value = this.jsonParser.getText();
                                JsonDecoder.LOG.debug("key=" + key + i + " valueArray=" + value);
                                getReceiver().literal(key + i, value);
                                currentToken = this.jsonParser.nextToken();
                                i++;
                            }
                        }
                    }
                    if (JsonToken.START_OBJECT == currentToken) {
                        if (this.jsonParser.getCurrentName() == null) {
                            break;
                        }
                    } else {
                        handleValue(currentToken, key);
                    }
                    try {
                        currentToken = this.jsonParser.nextToken();
                    } catch (JsonParseException jpe) {
                        LOG.info(
                                "JsonParseException happens at the end of an non JSON object, e.g. if it is JSONP",
                                jpe.getMessage());
                        currentToken = null;
                        break;
                    }
                }
            }
            JsonDecoder.LOG.debug("############################ End");
            if (STARTED) {
                getReceiver().endRecord();
                STARTED = false;

            }
        }
    } catch (final IOException e) {
        throw new MetafactureException(e);

    }
}

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

/**
 * The post operation accepts a json file, parses it and applies the social graph relationships to local profiles
 * @param request - the request//from   www . j av  a 2 s  . c o  m
 * @param response - the response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()
            && fileRequestParameters[0].getFileName().endsWith(".json")) {
        final InputStream inputStream = fileRequestParameters[0].getInputStream();
        final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
        JsonToken token = jsonParser.nextToken(); // get the first token
        if (token.equals(JsonToken.START_OBJECT)) {
            importFile(jsonParser, request);
        } else {
            throw new ServletException("Expected a start object token, got " + token);
        }
    } else {
        throw new ServletException("Expected to get a json file in post request");
    }
}

From source file:cz.cvut.kbss.jsonld.jackson.deserialization.JacksonJsonLdDeserializer.java

private Object parseJsonObject(JsonParser parser) throws IOException {
    Object value = null;//from w  ww.j  a  v  a 2s. c  o  m
    final JsonToken initialToken = parser.getCurrentToken();
    parser.setCodec(mapper);
    if (initialToken == JsonToken.START_ARRAY) {
        value = parser.readValueAs(new TypeReference<List<?>>() {
        });
    } else if (initialToken == JsonToken.START_OBJECT) {
        value = parser.readValueAs(new TypeReference<Map<?, ?>>() {
        });
    } else if (initialToken == JsonToken.VALUE_STRING) {
        value = parser.readValueAs(String.class);
    } else if (initialToken == JsonToken.VALUE_FALSE || initialToken == JsonToken.VALUE_TRUE) {
        value = parser.readValueAs(Boolean.class);
    } else if (initialToken == JsonToken.VALUE_NUMBER_FLOAT || initialToken == JsonToken.VALUE_NUMBER_INT) {
        value = parser.readValueAs(Number.class);
    } else if (initialToken == JsonToken.VALUE_NULL) {
        value = null;
    }
    return value;
}

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();/* w  w  w .  j a  va 2s.com*/

    parserWrapper.ensureObjectClosed();
    return new RawCouchDoc(new DocId(id), new Revision(rev));
}

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

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {

    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/*  www  .  ja va 2 s  . c  o m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }

    ShardState shardState = indexState.getShard(0);

    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }

    int count = 0;
    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse as many doc blocks as there are:
    while (true) {

        List<Document> children = null;
        Document parent = null;

        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("expected object");
        }

        // Parse parent + children for this one doc block:
        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                // Done with parent + child in this block
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name: " + token);
            }
            String f = parser.getText();
            if (f.equals("children")) {
                token = parser.nextToken();
                if (token != JsonToken.START_ARRAY) {
                    throw new IllegalArgumentException("expected array for children");
                }

                children = new ArrayList<Document>();

                // Parse each child:
                while (true) {
                    Document doc = addDocHandler.parseDocument(indexState, parser);
                    if (doc == null) {
                        break;
                    }
                    children.add(doc);
                }
            } else if (f.equals("parent")) {
                parent = addDocHandler.parseDocument(indexState, parser);
            } else {
                throw new IllegalArgumentException("unrecognized field name \"" + f + "\"");
            }
        }

        if (parent == null) {
            throw new IllegalArgumentException("missing parent");
        }
        if (children == null) {
            throw new IllegalArgumentException("missing children");
        }

        // Parent is last:
        children.add(parent);

        globalState.submitIndexingTask(shardState.getAddDocumentsJob(count, null, children, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    Throwable t = ctx.getError();
    if (t != null) {
        IOUtils.reThrow(t);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentBlockCount", count);
    return o.toString();
}

From source file:com.addthis.codec.config.ConfigTraversingParser.java

public ConfigTraversingParser(ConfigValue n, ObjectCodec codec) {
    super(0);/* www  .  ja v a2  s  .  com*/
    _objectCodec = codec;
    currentConfig = n;
    if (n.valueType() == LIST) {
        _nextToken = JsonToken.START_ARRAY;
        _nodeCursor = new ConfigNodeCursor.Array((ConfigList) n, null);
    } else if (n.valueType() == OBJECT) {
        _nextToken = JsonToken.START_OBJECT;
        _nodeCursor = new ConfigNodeCursor.Object((ConfigObject) n, null);
    } else { // value node
        _nodeCursor = new ConfigNodeCursor.RootValue(n, null);
    }
}

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

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {
    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/*from w w  w.j ava2  s  .c  o  m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);

    ShardState shardState = indexState.getShard(0);

    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }
    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }

    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse any number of documents to update:
    int count = 0;

    while (true) {
        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("missing object");
        }

        // Parse term: and fields:
        Term updateTerm = null;

        final Document doc = new Document();

        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name");
            }
            String f = parser.getText();
            if (f.equals("term")) {
                if (parser.nextToken() != JsonToken.START_OBJECT) {
                    throw new IllegalArgumentException("missing object");
                }

                // TODO: allow field to be specified only once, then
                // only text per document

                String field = null, term = null;

                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String f2 = parser.getText();
                    if (f2.equals("field")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        field = parser.getText();
                        // Ensure field is valid:
                        indexState.getField(field);
                    } else if (f2.equals("term")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        term = parser.getText();
                    } else {
                        throw new IllegalArgumentException("unexpected field " + f);
                    }
                }
                updateTerm = new Term(field, term);
            } else if (f.equals("fields")) {
                addDocHandler.parseFields(indexState, doc, parser);
            } else {
                boolean handled = false;
                for (AddDocumentHandler.PostHandle postHandle : addDocHandler.postHandlers) {
                    if (postHandle.invoke(indexState, f, parser, doc)) {
                        handled = true;
                        break;
                    }
                }
                if (!handled) {
                    throw new IllegalArgumentException("unrecognized field " + parser.getText());
                }
            }
        }

        if (updateTerm == null) {
            throw new IllegalArgumentException("missing term");
        }

        // TODO: this is dup'd code ... share better w/ AddDocHandler
        globalState.submitIndexingTask(shardState.getAddDocumentJob(count, updateTerm, doc, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentCount", count);
    return o.toString();
}

From source file:com.cinnober.msgcodec.json.TypeScannerJsonParserTest.java

@Test
public void testNested1() throws IOException {
    JsonParser p = new JsonFactory()
            .createParser("{\"a\":{\"c\":2, \"$type\":\"y\", \"d\":2.1}, \"$type\":\"x\", \"b\":1.1}");
    p.nextToken(); // START_OBJECT
    p.nextToken(); // FIELD_NAME
    TypeScannerJsonParser p2 = new TypeScannerJsonParser(p);
    assertEquals("x", p2.findType());

    assertNextField("a", p2);
    assertEquals(JsonToken.START_OBJECT, p2.nextToken());
    // start nested object
    p2.nextToken(); // FIELD_NAME
    assertEquals("y", p2.findType());
    assertNextField("c", p2);
    assertNextIntValue(2, p2);/* ww w . ja  v  a  2  s . c  o m*/
    assertNextField("d", p2);
    assertNextFloatValue(2.1, p2);
    assertEquals(JsonToken.END_OBJECT, p2.nextToken());
    // end nested object

    assertNextField("b", p2);
    assertNextFloatValue(1.1, p2);

    assertEquals(JsonToken.END_OBJECT, p2.nextToken());
    assertNull(p2.nextToken());
}