Java Code Examples for com.fasterxml.jackson.core.JsonParser#nextFieldName()
The following examples show how to use
com.fasterxml.jackson.core.JsonParser#nextFieldName() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArgWrapperJavaType.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
public Map<String, Object> readValue(ObjectMapper mapper, String json) throws IOException { Map<String, Object> args = new LinkedHashMap<>(); JsonParser jp = mapper.getFactory().createParser(json); DeserializationContext deserializationContext = ObjectMapperUtils.createDeserializationContext(mapper, jp); jp.nextToken(); for (String fieldName = jp.nextFieldName(); fieldName != null; fieldName = jp.nextFieldName()) { jp.nextToken(); ArgInfo argInfo = argInfos.get(fieldName); if (argInfo == null) { continue; } if (argInfo.deserializer == null) { argInfo.deserializer = deserializationContext.findRootValueDeserializer(argInfo.javaType); } args.put(fieldName, argInfo.deserializer.deserialize(jp, deserializationContext)); } return args; }
Example 2
Source File: JsonExtract.java From presto with Apache License 2.0 | 6 votes |
public T processJsonObject(JsonParser jsonParser) throws IOException { while (!jsonParser.nextFieldName(fieldName)) { if (!jsonParser.hasCurrentToken()) { throw new JsonParseException(jsonParser, "Unexpected end of object"); } if (jsonParser.getCurrentToken() == END_OBJECT) { // Unable to find matching field return null; } jsonParser.skipChildren(); // Skip nested structure if currently at the start of one } jsonParser.nextToken(); // Shift to first token of the value return delegate.extract(jsonParser); }
Example 3
Source File: BeanReader.java From jackson-jr with Apache License 2.0 | 6 votes |
private final Object _readWithUnknown(JSONReader r, JsonParser p, final Object bean, String propName) throws IOException { // first, skip current property handleUnknown(r, p, propName); // then do the rest with looping for (; (propName = p.nextFieldName()) != null; ) { BeanPropertyReader prop = findProperty(propName); if (prop == null) { handleUnknown(r, p, propName); continue; } prop.setValueFor(bean, prop.getReader().readNext(r, p)); } if (!p.hasToken(JsonToken.END_OBJECT)) { throw _reportProblem(p); } return bean; }
Example 4
Source File: NpmSearchIndexFacetGroup.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Method tries to load up next field (holding package name) and associated JSON Object (holding incomplete package * document) using given parser. If loaded up, the {@link #nextPackages} and {@link #origins} maps gets the new * document and this parser added under the key of the just loaded up package. If not loaded up (as parser got * depleted), the given parser is removed from the {@link #parsers} list. Returns {@false} if next was not found * in given parser, and parser should be removed from the list of parsers. */ private boolean tryNext(final JsonParser origin) throws IOException { String packageName = origin.nextFieldName(); if (packageName == null) { // depleted return false; } else { origin.nextToken(); NestedAttributesMap packageRoot = new NestedAttributesMap(packageName, origin.readValueAs(rawMapJsonTypeRef)); if (nextPackages.containsKey(packageName)) { packageRoot = NpmMetadataUtils.merge( packageName, ImmutableList.of(nextPackages.get(packageName), packageRoot) ); NpmMetadataUtils.shrink(packageRoot); } nextPackages.put(packageName, packageRoot); origins.put(packageName, origin); return true; } }
Example 5
Source File: BuildFilePythonResultDeserializer.java From buck with Apache License 2.0 | 5 votes |
private static Map<String, Object> deserializeObject(JsonParser jp) throws IOException { ImmutableMapWithNullValues.Builder<String, Object> builder = ImmutableMapWithNullValues.Builder.insertionOrder(); String fieldName; while ((fieldName = jp.nextFieldName()) != null) { builder.put(STRING_INTERNER.intern(fieldName), deserializeRecursive(jp, jp.nextToken())); } if (jp.getCurrentToken() != JsonToken.END_OBJECT) { throw new JsonParseException(jp, "Missing expected END_OBJECT"); } return builder.build(); }
Example 6
Source File: BuildFilePythonResultDeserializer.java From buck with Apache License 2.0 | 5 votes |
@Override public BuildFilePythonResult deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { if (jp.getCurrentToken() != JsonToken.START_OBJECT) { throw new JsonParseException(jp, "Missing expected START_OBJECT"); } ImmutableList<Map<String, Object>> values = ImmutableList.of(); ImmutableList<Map<String, Object>> diagnostics = ImmutableList.of(); Optional<String> profile = Optional.empty(); String fieldName; while ((fieldName = jp.nextFieldName()) != null) { switch (fieldName) { case "values": values = deserializeObjectList(jp); break; case "diagnostics": diagnostics = deserializeObjectList(jp); break; case "profile": profile = Optional.of(jp.nextTextValue()); break; default: throw new JsonParseException(jp, "Unexpected field name: " + fieldName); } } if (jp.getCurrentToken() != JsonToken.END_OBJECT) { throw new JsonParseException(jp, "Missing expected END_OBJECT"); } return BuildFilePythonResult.of(values, diagnostics, profile); }
Example 7
Source File: MapReader.java From jackson-jr with Apache License 2.0 | 5 votes |
@Override public Object read(JSONReader r, JsonParser p) throws IOException { MapBuilder b = r._mapBuilder(_mapType); String propName0 = p.nextFieldName(); if (propName0 == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.emptyMap(); } throw _reportWrongToken(p); } Object value = _valueReader.readNext(r, p); String propName = p.nextFieldName(); if (propName == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.singletonMap(propName0, value); } throw _reportWrongToken(p); } try { b = b.start().put(propName0, value); while (true) { b = b.put(propName, _valueReader.readNext(r, p)); propName = p.nextFieldName(); if (propName == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.build(); } throw _reportWrongToken(p); } } } catch (IllegalArgumentException e) { throw JSONObjectException.from(p, e.getMessage()); } }
Example 8
Source File: AnyReader.java From jackson-jr with Apache License 2.0 | 5 votes |
public Map<String, Object> readFromObject(JSONReader r, JsonParser p, MapBuilder b) throws IOException { // First, a minor optimization for empty Maps String k; if ((k = p.nextFieldName()) == null) { if (!p.hasToken(JsonToken.END_OBJECT)) { _reportNotEndObject(p); } return b.emptyMap(); } // and another for singletons... String key = fromKey(k); Object value = readNext(r, p); if ((k = p.nextFieldName()) == null) { if (!p.hasToken(JsonToken.END_OBJECT)) { _reportNotEndObject(p); } return b.singletonMap(key, value); } b = b.start().put(key, value); key = fromKey(k); value = readNext(r, p); // but then it's loop-de-loop try { b = b.put(key, value); while ((k = p.nextFieldName()) != null) { b = b.put(fromKey(k), readNext(r, p)); } } catch (IllegalArgumentException e) { throw JSONObjectException.from(p, e.getMessage()); } if (!p.hasToken(JsonToken.END_OBJECT)) { _reportNotEndObject(p); } return b.build(); }
Example 9
Source File: JacksonStreamTest.java From java-client-api with Apache License 2.0 | 5 votes |
/** Demonstrates how to use a JsonGenerator to stream output that you then persist to the * server using StringHandle (in this case, implicitly via writeAs). */ @Test public void testWriteStream() throws IOException { JacksonParserHandle handle = new JacksonParserHandle(); handle = docMgr.read(ORDER_URI, handle); JsonParser jp = handle.get(); if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } StringWriter jsonWriter = new StringWriter(); JsonGenerator jsonStream = (new ObjectMapper()).getFactory().createGenerator(jsonWriter); // in this sample case we're copying everything up to and excluding the order SerializedString order = new SerializedString("order"); do { jsonStream.copyCurrentEvent(jp); } while ( ! jp.nextFieldName(order) ); jsonStream.flush(); jsonStream.close(); docMgr.writeAs("testWriteStream.json", jsonWriter.toString()); JsonNode originalTree = docMgr.readAs(ORDER_URI, JsonNode.class); JsonNode streamedTree = docMgr.readAs("testWriteStream.json", JsonNode.class); assertEquals("customerName fields don't match", originalTree.get("customerName"), streamedTree.get("customerName")); assertEquals("shipToAddress fields don't match", originalTree.get("shipToAddress"), streamedTree.get("shipToAddress")); assertEquals("billingAddressRequired fields don't match", originalTree.get("billingAddressRequired"), streamedTree.get("billingAddressRequired")); }
Example 10
Source File: NpmSearchIndexFilter.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * Returns the next package from the {@link JsonParser}. */ @Nullable private static NestedAttributesMap getNext(final JsonParser origin) throws IOException { String packageName = origin.nextFieldName(); if (packageName == null) { // depleted return null; } else { origin.nextToken(); return new NestedAttributesMap(packageName, origin.readValueAs(rawMapJsonTypeRef)); } }
Example 11
Source File: CredentialModule.java From syndesis with Apache License 2.0 | 5 votes |
@Override public OAuthToken deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final Map<String, String> values = new HashMap<>(); String fieldName; while ((fieldName = p.nextFieldName()) != null) { final String nextValue = p.nextTextValue(); values.put(fieldName, nextValue); } return new OAuthToken(values.get("value"), values.get("secret")); }
Example 12
Source File: EntityBeanDeserializer.java From requery with Apache License 2.0 | 4 votes |
@Override public Object deserializeFromObject(JsonParser p, DeserializationContext ctxt) throws IOException { if (_nonStandardCreation || _needViewProcesing) { return super.deserializeFromObject(p, ctxt); } Object bean = null; if (p.hasTokenId(JsonTokenId.ID_FIELD_NAME)) { String propertyName = p.getCurrentName(); do { p.nextToken(); SettableBeanProperty property = _beanProperties.find(propertyName); if (property == null) { handleUnknownVanilla(p, ctxt, bean, propertyName); continue; } // lazily create the bean, the id property must be the first property if (bean == null) { if (propertyName.equals(_objectIdReader.propertyName.getSimpleName())) { // deserialize id Object id = property.deserialize(p, ctxt); ReadableObjectId objectId = ctxt.findObjectId(id, _objectIdReader.generator, _objectIdReader.resolver); bean = objectId == null ? null : objectId.resolve(); if (bean == null) { bean = _valueInstantiator.createUsingDefault(ctxt); property.set(bean, id); } } else { bean = _valueInstantiator.createUsingDefault(ctxt); } p.setCurrentValue(bean); } property.deserializeAndSet(p, ctxt, bean); } while ((propertyName = p.nextFieldName()) != null); } return bean; }
Example 13
Source File: BindMapHelper.java From kripton with Apache License 2.0 | 4 votes |
/** * Parse map. * * @param context the context * @param parser the parser * @param map the map * @param skipRead the skip read * @return the map */ static Map<String, Object> parseMap(AbstractContext context, JsonParser parser, Map<String, Object> map, boolean skipRead) { try { String key; Object value; if (!skipRead) { parser.nextToken(); } if (parser.currentToken() != JsonToken.START_OBJECT) { throw (new KriptonRuntimeException("Invalid input format")); } skipRead = false; do { if (skipRead) { key = parser.getCurrentName(); } else { key = parser.nextFieldName(); skipRead = true; } JsonToken token = parser.nextToken(); switch (token) { case START_ARRAY: // parse array value = parseList(context, parser, new ArrayList<Object>(), true); break; case VALUE_EMBEDDED_OBJECT: // parse submap value = parseMap(context, parser, new LinkedHashMap<String, Object>(), true); break; default: // parser.nextValue(); value = parser.getValueAsString(); } // value = parser.getText(); map.put(key, value); } while (parser.nextToken() != JsonToken.END_OBJECT); return map; } catch (IOException e) { e.printStackTrace(); throw (new KriptonRuntimeException(e)); } }
Example 14
Source File: TraceServiceElasticsearch.java From hawkular-apm with Apache License 2.0 | 4 votes |
@Override public Trace deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { Trace trace = new Trace(); String field = parser.nextFieldName(); while (field != null) { if (field.equals(ElasticsearchUtil.PROPERTIES_FIELD)) { parser.nextValue(); // Consume START_ARRAY while (parser.nextValue() == JsonToken.START_OBJECT) { // Ignore, just consume Property instance, as Trace class does not // retain this field, it is only used for searching in Elasticsearch context.readValue(parser, Property.class); } parser.nextValue(); // Consume END_ARRAY } else if (field.equals(ElasticsearchUtil.TRANSACTION_FIELD)) { trace.setTransaction(parser.nextTextValue()); } else if (field.equals(ElasticsearchUtil.HOST_ADDRESS_FIELD)) { trace.setHostAddress(parser.nextTextValue()); } else if (field.equals(ElasticsearchUtil.HOST_NAME_FIELD)) { trace.setHostName(parser.nextTextValue()); } else if (field.equals(ElasticsearchUtil.FRAGMENT_ID_FIELD)) { trace.setFragmentId(parser.nextTextValue()); } else if (field.equals(ElasticsearchUtil.NODES_FIELD)) { parser.nextValue(); // Consume START_ARRAY while (parser.nextValue() == JsonToken.START_OBJECT) { trace.getNodes().add(context.readValue(parser, Node.class)); } parser.nextValue(); // Consume END_ARRAY } else if (field.equals(ElasticsearchUtil.TIMESTAMP_FIELD)) { trace.setTimestamp(parser.nextLongValue(0)); } else if (field.equals(ElasticsearchUtil.TRACE_ID_FIELD)) { trace.setTraceId(parser.nextTextValue()); } field = parser.nextFieldName(); } return trace; }
Example 15
Source File: MapReader.java From jackson-jr with Apache License 2.0 | 4 votes |
@Override public Object readNext(JSONReader r, JsonParser p) throws IOException { if (p.nextToken() != JsonToken.START_OBJECT) { if (p.hasToken(JsonToken.VALUE_NULL)) { return null; } throw JSONObjectException.from(p, "Unexpected token %s; should get START_OBJECT", p.currentToken()); } MapBuilder b = r._mapBuilder(_mapType); String propName0 = p.nextFieldName(); if (propName0 == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.emptyMap(); } throw _reportWrongToken(p); } Object value = _valueReader.readNext(r, p); String propName = p.nextFieldName(); if (propName == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.singletonMap(propName0, value); } throw _reportWrongToken(p); } try { b = b.start().put(propName0, value); while (true) { b = b.put(propName, _valueReader.readNext(r, p)); propName = p.nextFieldName(); if (propName == null) { if (p.hasToken(JsonToken.END_OBJECT)) { return b.build(); } throw _reportWrongToken(p); } } } catch (IllegalArgumentException e) { throw JSONObjectException.from(p, e.getMessage()); } }
Example 16
Source File: Policy.java From spring-vault with Apache License 2.0 | 4 votes |
@Override public Policy deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Assert.isTrue(p.getCurrentToken() == JsonToken.START_OBJECT, "Expected START_OBJECT, got: " + p.getCurrentToken()); String fieldName = p.nextFieldName(); Set<Rule> rules = new LinkedHashSet<>(); if ("path".equals(fieldName)) { p.nextToken(); Assert.isTrue(p.getCurrentToken() == JsonToken.START_OBJECT, "Expected START_OBJECT, got: " + p.getCurrentToken()); p.nextToken(); while (p.currentToken() == JsonToken.FIELD_NAME) { String path = p.getCurrentName(); p.nextToken(); Assert.isTrue(p.getCurrentToken() == JsonToken.START_OBJECT, "Expected START_OBJECT, got: " + p.getCurrentToken()); Rule rule = p.getCodec().readValue(p, Rule.class); rules.add(rule.withPath(path)); JsonToken jsonToken = p.nextToken(); if (jsonToken == JsonToken.END_OBJECT) { break; } } Assert.isTrue(p.getCurrentToken() == JsonToken.END_OBJECT, "Expected END_OBJECT, got: " + p.getCurrentToken()); p.nextToken(); } Assert.isTrue(p.getCurrentToken() == JsonToken.END_OBJECT, "Expected END_OBJECT, got: " + p.getCurrentToken()); return Policy.of(rules); }
Example 17
Source File: BeanReader.java From jackson-jr with Apache License 2.0 | 4 votes |
private final Object _readBean(JSONReader r, JsonParser p, final Object bean) throws IOException { // 13-Dec-2017, tatu: Unrolling is unpredictable business, and // performance does not seem linear. In fact, choices of 2 or 8 unrolls // seem to have about same performance for our test (but in between less... :) ) int ix = p.nextFieldName(_fieldMatcher); final BeanPropertyReader[] readers = _fieldReaders; while (ix >= 0) { BeanPropertyReader prop = readers[ix]; // elem #1 Object value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #2 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); /* if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #3 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #4 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #5 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #6 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #7 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); if ((ix = p.nextFieldName(_fieldMatcher)) < 0) break; prop = readers[ix]; // elem #8 value = prop.getReader().readNext(r, p); prop.setValueFor(bean, value); */ // and then for next loop ix = p.nextFieldName(_fieldMatcher); } if (ix != FieldNameMatcher.MATCH_END_OBJECT) { if (ix == FieldNameMatcher.MATCH_UNKNOWN_NAME) { return _readWithUnknown(r, p, bean, p.currentName()); } throw _reportProblem(p); } return bean; }
Example 18
Source File: BatchResultDeserializer.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
@Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { int took = 0; boolean errors = false; Error error = null; int status = -1; List<BatchItemResult> items = null; String fieldName; while ((fieldName = p.nextFieldName()) != null) { switch (fieldName) { case "took": { took = p.nextIntValue(-1); break; } case "errors": { errors = p.nextBooleanValue(); break; } case "status": { status = p.nextIntValue(-1); break; } case "error": { p.nextValue(); // skip to START_OBJECT or VALUE_NULL JsonDeserializer<Object> typeDeserializer = ctxt.findNonContextualValueDeserializer(ctxt.constructType(Error.class)); error = (Error) typeDeserializer.deserialize(p, ctxt); break; } case "items": { if (errors) { items = new ArrayList<>(); p.nextValue(); // skip to START_ARRAY p.nextValue(); // skip to START_OBJECT ObjectMapper mapper = (ObjectMapper) p.getCodec(); MappingIterator<BatchItemResult> batchResultItemMappingIterator = mapper.readValues(p, BatchItemResult.class); while (batchResultItemMappingIterator.hasNext()) { items.add(batchResultItemMappingIterator.next()); } } break; } } } return new BatchResult(took, errors, error, status, items); }
Example 19
Source File: BulkResultDeserializer.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
@Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { int took = 0; boolean errors = false; BulkError error = null; int status = -1; List<BulkResultItem> items = null; String fieldName; while ((fieldName = p.nextFieldName()) != null) { switch (fieldName) { case "took": { took = p.nextIntValue(-1); break; } case "errors": { errors = p.nextBooleanValue(); break; } case "status": { status = p.nextIntValue(-1); break; } case "error": { p.nextValue(); // skip to START_OBJECT or VALUE_NULL JsonDeserializer<Object> typeDeserializer = ctxt.findNonContextualValueDeserializer(ctxt.constructType(BulkError.class)); error = (BulkError) typeDeserializer.deserialize(p, ctxt); break; } case "items": { if (errors) { items = new ArrayList<>(); p.nextValue(); // skip to START_ARRAY p.nextValue(); // skip to START_OBJECT ObjectMapper mapper = (ObjectMapper) p.getCodec(); MappingIterator<BulkResultItem> bulkResultItemMappingIterator = mapper.readValues(p, BulkResultItem.class); while (bulkResultItemMappingIterator.hasNext()) { items.add(bulkResultItemMappingIterator.next()); } } break; } } } return new BufferedBulkResult(took, errors, error, status, items); }