Java Code Examples for com.fasterxml.jackson.core.JsonParser#getCurrentToken()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#getCurrentToken() . 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: RecordDeserialiser.java    From octarine with Apache License 2.0 6 votes vote down vote up
@Override
public Record applyUnsafe(JsonParser parser) throws IOException {
    List<Value> values = new ArrayList<>();

    if (parser.nextToken() == JsonToken.END_OBJECT) {
        return Record.empty();
    }

    /*
     * When the parser has hit the end of input nextToken() will always return null.
     * So need to prevent infinite loops we check the parser closed flag.
     */
    while (!parser.isClosed() && (parser.nextValue() != JsonToken.END_OBJECT)) {
        String fieldName = parser.getCurrentName();
        if (JsonToken.VALUE_NULL != parser.getCurrentToken()) {
            Optional<Value> result = parserMapper.apply(fieldName, parser);
            if (result.isPresent()) {
                values.add(result.get());
            } else {
                consumeUnwanted(parser);
            }
        }
    }

    return Record.of(values);
}
 
Example 2
Source File: JsonldBeanDeserializerModifier.java    From jackson-jsonld with MIT License 6 votes vote down vote up
private Object parseJsonldObject(JsonParser jp) throws IOException {
    Object rval = null;
    final JsonToken initialToken = jp.getCurrentToken();

    if (initialToken == JsonToken.START_ARRAY) {
        jp.setCodec(mapper);
        rval = jp.readValueAs(List.class);
    } else if (initialToken == JsonToken.START_OBJECT) {
        jp.setCodec(mapper);
        rval = jp.readValueAs(Map.class);
    } else if (initialToken == JsonToken.VALUE_STRING) {
        jp.setCodec(mapper);
        rval = jp.readValueAs(String.class);
    } else if (initialToken == JsonToken.VALUE_FALSE || initialToken == JsonToken.VALUE_TRUE) {
        jp.setCodec(mapper);
        rval = jp.readValueAs(Boolean.class);
    } else if (initialToken == JsonToken.VALUE_NUMBER_FLOAT
            || initialToken == JsonToken.VALUE_NUMBER_INT) {
        jp.setCodec(mapper);
        rval = jp.readValueAs(Number.class);
    } else if (initialToken == JsonToken.VALUE_NULL) {
        rval = null;
    }
    return rval;
}
 
Example 3
Source File: StoneSerializers.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
public T deserialize(JsonParser p) throws IOException, JsonParseException {
    if (p.getCurrentToken() == JsonToken.VALUE_NULL) {
        p.nextToken();
        return null;
    } else {
        return underlying.deserialize(p);
    }
}
 
Example 4
Source File: ClientCsdlFunction.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientCsdlFunction doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

  final ClientCsdlFunction functionImpl = new ClientCsdlFunction();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Name".equals(jp.getCurrentName())) {
        functionImpl.setName(jp.nextTextValue());
      } else if ("IsBound".equals(jp.getCurrentName())) {
        functionImpl.setBound(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("IsComposable".equals(jp.getCurrentName())) {
        functionImpl.setComposable(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("EntitySetPath".equals(jp.getCurrentName())) {
        functionImpl.setEntitySetPath(jp.nextTextValue());
      } else if ("Parameter".equals(jp.getCurrentName())) {
        jp.nextToken();
        functionImpl.getParameters().add(jp.readValueAs(ClientCsdlParameter.class));
      } else if ("ReturnType".equals(jp.getCurrentName())) {
        functionImpl.setReturnType(parseReturnType(jp, "Function"));
      } else if ("Annotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        functionImpl.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
      }
    }
  }

  return functionImpl;
}
 
Example 5
Source File: JSR310LocalDateDeserializer.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    switch(parser.getCurrentToken()) {
        case START_ARRAY:
            if(parser.nextToken() == JsonToken.END_ARRAY) {
                return null;
            }
            int year = parser.getIntValue();

            parser.nextToken();
            int month = parser.getIntValue();

            parser.nextToken();
            int day = parser.getIntValue();

            if(parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
            }
            return LocalDate.of(year, month, day);

        case VALUE_STRING:
            String string = parser.getText().trim();
            if(string.length() == 0) {
                return null;
            }
            return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
    }
    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
}
 
Example 6
Source File: UserAccessTokenBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public UserAccessToken parseOnJacksonAsString(JsonParser jacksonParser) throws Exception {
  UserAccessToken instance = new UserAccessToken();
  String fieldName;
  if (jacksonParser.getCurrentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "creationDate":
          // field creationDate (mapped with "creationDate")
          instance.setCreationDate(PrimitiveUtils.readLong(jacksonParser.getText(), 0L));
        break;
        case "uid":
          // field uid (mapped with "uid")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.setUid(jacksonParser.getText());
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 7
Source File: JoynrUntypedObjectDeserializer.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
/**
 * All joynr objects are serialized with type information, so deserialize them as such
 */
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.START_OBJECT) {
        return super.deserializeWithType(jp, ctxt, typeDeserializer);
    }

    return super.deserialize(jp, ctxt);
}
 
Example 8
Source File: ClientCsdlAction.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientCsdlAction doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

  final ClientCsdlAction action = new ClientCsdlAction();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Name".equals(jp.getCurrentName())) {
        action.setName(jp.nextTextValue());
      } else if ("IsBound".equals(jp.getCurrentName())) {
        action.setBound(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("EntitySetPath".equals(jp.getCurrentName())) {
        action.setEntitySetPath(jp.nextTextValue());
      } else if ("Parameter".equals(jp.getCurrentName())) {
        jp.nextToken();
        action.getParameters().add(jp.readValueAs(ClientCsdlParameter.class));
      } else if ("ReturnType".equals(jp.getCurrentName())) {
        action.setReturnType(parseReturnType(jp, "Action"));
      } else if ("Annotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        action.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
      }
    }
  }

  return action;
}
 
Example 9
Source File: BlockHexDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Block deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                byte[] payload = HexUtil.hexStringToByteArray(p.getValueAsString()); // convert  to hex
                return context.getParams().getDefaultSerializer().makeBlock(payload);
            } catch (ProtocolException e) {
                throw new InvalidFormatException(p, "Invalid Block", p.getValueAsString(), Block.class);
            }
        default:
            return (Block) ctxt.handleUnexpectedToken(Block.class, p);
    }
}
 
Example 10
Source File: ClientCsdlEntityType.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected CsdlEntityType doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

  final ClientCsdlEntityType entityType = new ClientCsdlEntityType();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Name".equals(jp.getCurrentName())) {
        entityType.setName(jp.nextTextValue());
      } else if ("Abstract".equals(jp.getCurrentName())) {
        entityType.setAbstract(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("BaseType".equals(jp.getCurrentName())) {
        entityType.setBaseType(jp.nextTextValue());
      } else if ("OpenType".equals(jp.getCurrentName())) {
        entityType.setOpenType(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("HasStream".equals(jp.getCurrentName())) {
        entityType.setHasStream(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("Key".equals(jp.getCurrentName())) {
        jp.nextToken();
        ClientCsdlEntityKey keyImpl = jp.readValueAs(ClientCsdlEntityKey.class);
        entityType.setKey(keyImpl.getPropertyRefs());
      } else if ("Property".equals(jp.getCurrentName())) {
        jp.nextToken();
        entityType.getProperties().add(jp.readValueAs(ClientCsdlProperty.class));
      } else if ("NavigationProperty".equals(jp.getCurrentName())) {
        jp.nextToken();
        entityType.getNavigationProperties().add(jp.readValueAs(ClientCsdlNavigationProperty.class));
      } else if ("Annotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        entityType.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
      }
    }
  }

  return entityType;
}
 
Example 11
Source File: CountBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Count parseOnJacksonAsString(JsonParser jacksonParser) throws Exception {
  Count instance = new Count();
  String fieldName;
  if (jacksonParser.getCurrentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "count":
          // field count (mapped with "count")
          instance.setCount(PrimitiveUtils.readInteger(jacksonParser.getText(), 0));
        break;
        case "title":
          // field title (mapped with "title")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.setTitle(jacksonParser.getText());
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 12
Source File: LibraryUpdaterTask.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
private void parseDownloadUrls(JsonParser parser, ContentValues result) throws JsonParseException, IOException {
		// parser points at begin object token right now
		if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
			while (parser.nextValue() != JsonToken.END_OBJECT) {
				String fieldName = parser.getCurrentName();
				
				if (downloadUrlFields.contains(fieldName)) {
					result.put(fieldName + "url", parser.getValueAsString());
				}
			}
		}
//		else we must not have any download urls (null, '', something like that.)
	}
 
Example 13
Source File: Seminar2StudentBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Seminar2Student parseOnJacksonAsString(JsonParser jacksonParser) throws Exception {
  Seminar2Student instance = new Seminar2Student();
  String fieldName;
  if (jacksonParser.getCurrentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "id":
          // field id (mapped with "id")
          instance.id=PrimitiveUtils.readLong(jacksonParser.getText(), 0L);
        break;
        case "seminarId":
          // field seminarId (mapped with "seminarId")
          instance.seminarId=PrimitiveUtils.readLong(jacksonParser.getText(), 0L);
        break;
        case "studentId":
          // field studentId (mapped with "studentId")
          instance.studentId=PrimitiveUtils.readLong(jacksonParser.getText(), 0L);
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 14
Source File: Sha256HashDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Sha256Hash deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            return Sha256Hash.wrap(p.getValueAsString());
        default:
            return (Sha256Hash) ctxt.handleUnexpectedToken(Sha256Hash.class, p);
    }
}
 
Example 15
Source File: PersonBindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Person parseOnJacksonAsString(JsonParser jacksonParser) throws Exception {
  Person instance = new Person();
  String fieldName;
  if (jacksonParser.getCurrentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "birthDate":
          // field birthDate (mapped with "birthDate")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            // using type adapter sqlite.adapter.example01.DateAdapter
            instance.setBirthDate(TypeAdapterUtils.toJava(DateAdapter.class, PrimitiveUtils.readLong(jacksonParser.getText(), null)));
          }
        break;
        case "id":
          // field id (mapped with "id")
          instance.setId(PrimitiveUtils.readLong(jacksonParser.getText(), 0L));
        break;
        case "name":
          // field name (mapped with "name")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.setName(jacksonParser.getText());
          }
        break;
        case "surname":
          // field surname (mapped with "surname")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.setSurname(jacksonParser.getText());
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 16
Source File: StoneSerializer.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
protected static void expectStartArray(JsonParser p) throws IOException, JsonParseException {
    if (p.getCurrentToken() != JsonToken.START_ARRAY) {
        throw new JsonParseException(p, "expected array value.");
    }
    p.nextToken();
}
 
Example 17
Source File: PropertiesDeserializer.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
@Override
public Properties deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    if (START_OBJECT == p.getCurrentToken()) {
        final Properties properties = new Properties();
        final Deque<String> stack = new ArrayDeque<>();
        final ArrayList<String> array = new ArrayList<>();
        for (JsonToken nextToken = p.nextToken(); nextToken != END_OBJECT || !stack.isEmpty(); nextToken = p.nextToken()) {
            switch(nextToken) {
                case FIELD_NAME:
                    stack.addLast(p.getCurrentName());
                    break;
                case VALUE_STRING:
                case VALUE_NUMBER_INT:
                case VALUE_NUMBER_FLOAT:
                case VALUE_TRUE:
                case VALUE_FALSE:
                    if (p.getParsingContext().inArray()) {
                        array.add(p.getText());
                    } else {
                        properties.put(DOT_JOINER.join(stack), p.getText());
                        stack.removeLast();
                    }
                    break;
                case START_OBJECT:
                    if (p.getParsingContext().inArray()) {
                        throw UnsupportedTypeException.from(p, START_OBJECT, "Nested objects within arrays not allowed in Properties object.");
                    }
                    break;
                case END_OBJECT:
                    stack.removeLast();
                    break;
                case START_ARRAY:
                    array.clear();
                    break;
                case END_ARRAY:
                    properties.put(DOT_JOINER.join(stack), COMMA_JOINER.join(array));
                    stack.removeLast();
                    break;
                case VALUE_NULL:
                    throw UnsupportedTypeException.from(p, VALUE_NULL, "Null values not allowed in Properties object.");
                case VALUE_EMBEDDED_OBJECT:
                    throw UnsupportedTypeException.from(p, VALUE_EMBEDDED_OBJECT, "Embedded object not allowed as part of Properties object.");
                case NOT_AVAILABLE:
                    break;
            }
        }
        return properties;
    } else {
        throw ctx.wrongTokenException(p, handledType(), START_OBJECT, "Expected nested object for Properties mapping.");
    }
}
 
Example 18
Source File: JsonInput.java    From protostuff with Apache License 2.0 4 votes vote down vote up
private <T> int readFieldNumber(final Schema<T> schema, final JsonParser parser)
        throws IOException
{
    for (; ; )
    {
        if (parser.nextToken() == END_OBJECT)
            return 0;

        if (parser.getCurrentToken() != FIELD_NAME)
        {
            throw new JsonInputException("Expected token: $field: but was " +
                    parser.getCurrentToken() + " on message " + schema.messageFullName());
        }

        final String name = parser.getCurrentName();

        // move to the next token
        parser.nextToken();

        // skip null value
        if (parser.getCurrentToken() == VALUE_NULL)
        {
            continue;
        }

        int number = numeric ? Integer.parseInt(name) : schema.getFieldNumber(name);

        if (number == 0)
        {
            // we can skip this unknown field
            if (!parser.getCurrentToken().isScalarValue())
            {
                skipField(parser);
            }
            continue;
        }

        if (parser.getCurrentToken() == START_ARRAY)
        {
            JsonToken jt = parser.nextToken();

            // if empty array, read the next field
            if (jt == END_ARRAY)
            {
                continue;
            }

            if (jt == VALUE_NULL)
            {
                // skip null elements
                //noinspection StatementWithEmptyBody
                while (VALUE_NULL == (jt = parser.nextToken()))
                    ;

                // all elements were null.
                if (jt == END_ARRAY)
                {
                    continue;
                }
            }

            lastRepeated = true;
            lastName = name;
            lastNumber = number;

            return number;
        }

        lastName = name;
        lastNumber = number;

        return number;
    }
}
 
Example 19
Source File: DbxDeltaC.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
public static <C, MD extends Dumpable> DbxDeltaC<C> read(JsonParser parser, JsonReader<MD> metadataReader, Collector<DbxDeltaC.Entry<MD>, C> entryCollector)
    throws IOException, JsonReadException
{
    JsonLocation top = JsonReader.expectObjectStart(parser);

    Boolean reset = null;
    C entries = null;
    String cursor = null;
    Boolean has_more = null;

    while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
        String fieldName = parser.getCurrentName();
        JsonReader.nextToken(parser);

        int fi = FM.get(fieldName);
        try {
            if (fi == -1) {
                // Unknown field.  Skip over it.
                JsonReader.skipValue(parser);
                continue;
            }
            switch (fi) {
                case FM_reset: reset = JsonReader.BooleanReader.readField(parser, fieldName, reset); break;
                case FM_entries:
                    JsonReader<Entry<MD>> entryReader = new Entry.Reader<MD>(metadataReader);
                    entries = JsonArrayReader.mk(entryReader, entryCollector).readField(parser, fieldName, entries);
                    break;
                case FM_cursor: cursor = JsonReader.StringReader.readField(parser, fieldName, cursor); break;
                case FM_has_more: has_more = JsonReader.BooleanReader.readField(parser, fieldName, has_more); break;
                default:
                    throw new AssertionError("bad index: " + fi + ", field = \"" + fieldName + "\"");
            }
        }
        catch (JsonReadException ex) {
            throw ex.addFieldContext(fieldName);
        }
    }

    JsonReader.expectObjectEnd(parser);

    if (reset == null) throw new JsonReadException("missing field \"path\"", top);
    if (entries == null) throw new JsonReadException("missing field \"entries\"", top);
    if (cursor == null) throw new JsonReadException("missing field \"cursor\"", top);
    if (has_more == null) throw new JsonReadException("missing field \"has_more\"", top);

    return new DbxDeltaC<C>(reset, entries, cursor, has_more);
}
 
Example 20
Source File: JsonUtilities.java    From azure-storage-android with Apache License 2.0 2 votes vote down vote up
/***
 * Reserved for internal use. Asserts that the current token of the parser is the start of an object.
 * 
 * @param parser
 *            The {@link JsonParser} whose current token to check.
 */
public static void assertIsStartObjectJsonToken(final JsonParser parser) throws JsonParseException {
    if (!(parser.getCurrentToken() == JsonToken.START_OBJECT)) {
        throw new JsonParseException(SR.EXPECTED_START_OBJECT, parser.getCurrentLocation());
    }
}