private void skipToField(JsonParser jp, String fieldName, ParseState state)
     throws JsonParseException, IOException {
   String lastFieldName = null;
   while (jp.getCurrentToken() != null) {
     switch (jp.getCurrentToken()) {
       case FIELD_NAME:
         lastFieldName = jp.getCurrentName();
         jp.nextToken();
         break;
       case START_OBJECT:
         if (!state.inRow) {
           state.inRow = true;
           jp.nextToken();
         } else {
           if (isInField(fieldName, lastFieldName)) {
             return;
           } else {
             jp.skipChildren();
           }
         }
         break;
       default:
         if (isInField(fieldName, lastFieldName)) {
           jp.nextToken();
           return;
         }
         jp.nextToken();
         break;
     }
   }
 }
Пример #2
0
 protected Object _unwrapAndDeserialize(
     JsonParser jp, DeserializationContext ctxt, JavaType rootType, JsonDeserializer<Object> deser)
     throws IOException, JsonParseException, JsonMappingException {
   SerializedString rootName = _provider.findExpectedRootName(ctxt.getConfig(), rootType);
   if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
     throw JsonMappingException.from(
         jp,
         "Current token not START_OBJECT (needed to unwrap root name '"
             + rootName
             + "'), but "
             + jp.getCurrentToken());
   }
   if (jp.nextToken() != JsonToken.FIELD_NAME) {
     throw JsonMappingException.from(
         jp,
         "Current token not FIELD_NAME (to contain expected root name '"
             + rootName
             + "'), but "
             + jp.getCurrentToken());
   }
   String actualName = jp.getCurrentName();
   if (!rootName.getValue().equals(actualName)) {
     throw JsonMappingException.from(
         jp,
         "Root name '"
             + actualName
             + "' does not match expected ('"
             + rootName
             + "') for type "
             + rootType);
   }
   // ok, then move to value itself....
   jp.nextToken();
   Object result;
   if (_valueToUpdate == null) {
     result = deser.deserialize(jp, ctxt);
   } else {
     deser.deserialize(jp, ctxt, _valueToUpdate);
     result = _valueToUpdate;
   }
   // and last, verify that we now get matching END_OBJECT
   if (jp.nextToken() != JsonToken.END_OBJECT) {
     throw JsonMappingException.from(
         jp,
         "Current token not END_OBJECT (to match wrapper object with root name '"
             + rootName
             + "'), but "
             + jp.getCurrentToken());
   }
   return result;
 }
Пример #3
0
 @Override
 public DateMidnight deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   // We'll accept either long (timestamp) or array:
   if (jp.isExpectedStartArrayToken()) {
     jp.nextToken(); // VALUE_NUMBER_INT
     int year = jp.getIntValue();
     jp.nextToken(); // VALUE_NUMBER_INT
     int month = jp.getIntValue();
     jp.nextToken(); // VALUE_NUMBER_INT
     int day = jp.getIntValue();
     if (jp.nextToken() != JsonToken.END_ARRAY) {
       throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after DateMidnight ints");
     }
     return new DateMidnight(year, month, day);
   }
   switch (jp.getCurrentToken()) {
     case VALUE_NUMBER_INT:
       return new DateMidnight(jp.getLongValue());
     case VALUE_STRING:
       DateTime local = parseLocal(jp);
       if (local == null) {
         return null;
       }
       return local.toDateMidnight();
   }
   throw ctxt.wrongTokenException(
       jp, JsonToken.START_ARRAY, "expected JSON Array, Number or String");
 }
Пример #4
0
  public final void copyCurrentStructure(JsonParser jp)
      throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();

    // Let's handle field-name separately first
    if (t == JsonToken.FIELD_NAME) {
      writeFieldName(jp.getCurrentName());
      t = jp.nextToken();
      // fall-through to copy the associated value
    }

    switch (t) {
      case START_ARRAY:
        writeStartArray();
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          copyCurrentStructure(jp);
        }
        writeEndArray();
        break;
      case START_OBJECT:
        writeStartObject();
        while (jp.nextToken() != JsonToken.END_OBJECT) {
          copyCurrentStructure(jp);
        }
        writeEndObject();
        break;
      default: // others are simple:
        copyCurrentEvent(jp);
    }
  }
 private void reportIllegal(JsonParser parser, JsonToken expToken) throws IOException {
   JsonToken curr = parser.getCurrentToken();
   String msg = "Expected token " + expToken + "; got " + curr;
   if (curr == JsonToken.FIELD_NAME) {
     msg += " (current field name '" + parser.getCurrentName() + "')";
   }
   msg += ", location: " + parser.getTokenLocation();
   throw new IllegalStateException(msg);
 }
Пример #6
0
    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
      // We'll accept either long (timestamp) or array:
      if (jp.isExpectedStartArrayToken()) {
        jp.nextToken(); // VALUE_NUMBER_INT
        int year = jp.getIntValue();
        jp.nextToken(); // VALUE_NUMBER_INT
        int month = jp.getIntValue();
        jp.nextToken(); // VALUE_NUMBER_INT
        int day = jp.getIntValue();
        jp.nextToken(); // VALUE_NUMBER_INT
        int hour = jp.getIntValue();
        jp.nextToken(); // VALUE_NUMBER_INT
        int minute = jp.getIntValue();
        jp.nextToken(); // VALUE_NUMBER_INT
        int second = jp.getIntValue();
        // let's leave milliseconds optional?
        int millisecond = 0;
        if (jp.nextToken() != JsonToken.END_ARRAY) { // VALUE_NUMBER_INT
          millisecond = jp.getIntValue();
          jp.nextToken(); // END_ARRAY?
        }
        if (jp.getCurrentToken() != JsonToken.END_ARRAY) {
          throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after LocalDateTime ints");
        }
        return new LocalDateTime(year, month, day, hour, minute, second, millisecond);
      }

      switch (jp.getCurrentToken()) {
        case VALUE_NUMBER_INT:
          return new LocalDateTime(jp.getLongValue());
        case VALUE_STRING:
          DateTime local = parseLocal(jp);
          if (local == null) {
            return null;
          }
          return local.toLocalDateTime();
      }
      throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Array or Number");
    }
  /**
   * This method is needed by some specialized bean deserializers, and also called by some {@link
   * #deserializeAndSet} implementations.
   *
   * <p>Pre-condition is that passed parser must point to the first token that should be consumed to
   * produce the value (the only value for scalars, multiple for Objects and Arrays).
   *
   * <p>Note that this method is final for performance reasons: to override functionality you must
   * override other methods that call this method; this method should also not be called directly
   * unless you really know what you are doing (and probably not even then).
   */
  public final Object deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();

    if (t == JsonToken.VALUE_NULL) {
      return (_nullProvider == null) ? null : _nullProvider.nullValue(ctxt);
    }
    if (_valueTypeDeserializer != null) {
      return _valueDeserializer.deserializeWithType(jp, ctxt, _valueTypeDeserializer);
    }
    return _valueDeserializer.deserialize(jp, ctxt);
  }
Пример #8
0
 @Override
 public ReadablePeriod deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   // TODO: perhaps support array of numbers...
   // if (jp.isExpectedStartArrayToken()) { ]
   switch (jp.getCurrentToken()) {
     case VALUE_NUMBER_INT: // assume it's millisecond count
       return new Period(jp.getLongValue());
     case VALUE_STRING:
       return new Period(jp.getText());
   }
   throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Number or String");
 }
  @Override
  public EnumMap<?, ?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    // Ok: must point to START_OBJECT
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
      return _deserializeFromEmpty(jp, ctxt);
    }
    EnumMap result = constructMap();
    final JsonDeserializer<Object> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;

    while ((jp.nextToken()) == JsonToken.FIELD_NAME) {
      String keyName = jp.getCurrentName(); // just for error message
      // but we need to let key deserializer handle it separately, nonetheless
      Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt);
      if (key == null) {
        if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
          throw ctxt.weirdStringException(
              keyName,
              _enumClass,
              "value not one of declared Enum instance names for " + _mapType.getKeyType());
        }
        /* 24-Mar-2012, tatu: Null won't work as a key anyway, so let's
         *  just skip the entry then. But we must skip the value as well, if so.
         */
        jp.nextToken();
        jp.skipChildren();
        continue;
      }
      // And then the value...
      JsonToken t = jp.nextToken();
      /* note: MUST check for nulls separately: deserializers will
       * not handle them (and maybe fail or return bogus data)
       */
      Object value;

      try {
        if (t == JsonToken.VALUE_NULL) {
          value = valueDes.getNullValue(ctxt);
        } else if (typeDeser == null) {
          value = valueDes.deserialize(jp, ctxt);
        } else {
          value = valueDes.deserializeWithType(jp, ctxt, typeDeser);
        }
      } catch (Exception e) {
        wrapAndThrow(e, result, keyName);
        return null;
      }
      result.put(key, value);
    }
    return result;
  }
  /** This is the trickiest thing to handle, since property we are looking for may be anywhere... */
  @Override
  public Object deserializeTypedFromObject(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
    // but first, sanity check to ensure we have START_OBJECT or FIELD_NAME
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.START_OBJECT) {
      t = jp.nextToken();
    } else if (t != JsonToken.FIELD_NAME) {
      throw ctxt.wrongTokenException(
          jp,
          JsonToken.START_OBJECT,
          "need JSON Object to contain As.PROPERTY type information (for class "
              + baseTypeName()
              + ")");
    }
    // Ok, let's try to find the property. But first, need token buffer...
    TokenBuffer tb = null;

    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
      String name = jp.getCurrentName();
      jp.nextToken(); // to point to the value
      if (_propertyName.equals(name)) { // gotcha!
        JsonDeserializer<Object> deser = _findDeserializer(ctxt, jp.getText());
        // deserializer should take care of closing END_OBJECT as well
        if (tb != null) {
          jp = JsonParserSequence.createFlattened(tb.asParser(jp), jp);
        }
        /* Must point to the next value; tb had no current, jp
         * pointed to VALUE_STRING:
         */
        jp.nextToken(); // to skip past String value
        // deserializer should take care of closing END_OBJECT as well
        return deser.deserialize(jp, ctxt);
      }
      if (tb == null) {
        tb = new TokenBuffer(null);
      }
      tb.writeFieldName(name);
      tb.copyCurrentStructure(jp);
    }
    // Error if we get here...
    throw ctxt.wrongTokenException(
        jp,
        JsonToken.FIELD_NAME,
        "missing property '"
            + _propertyName
            + "' that is to contain type id  (for class "
            + baseTypeName()
            + ")");
  }
  /** Offlined version used when we do not use the default deserialization method. */
  protected final String[] _deserializeCustom(
      JsonParser p, DeserializationContext ctxt, String[] old) throws IOException {
    final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
    int ix;
    Object[] chunk;

    if (old == null) {
      ix = 0;
      chunk = buffer.resetAndStart();
    } else {
      ix = old.length;
      chunk = buffer.resetAndStart(old, ix);
    }

    final JsonDeserializer<String> deser = _elementDeserializer;

    try {
      while (true) {
        /* 30-Dec-2014, tatu: This may look odd, but let's actually call method
         *   that suggest we are expecting a String; this helps with some formats,
         *   notably XML. Note, however, that while we can get String, we can't
         *   assume that's what we use due to custom deserializer
         */
        String value;
        if (p.nextTextValue() == null) {
          JsonToken t = p.getCurrentToken();
          if (t == JsonToken.END_ARRAY) {
            break;
          }
          // Ok: no need to convert Strings, but must recognize nulls
          value =
              (t == JsonToken.VALUE_NULL) ? deser.getNullValue(ctxt) : deser.deserialize(p, ctxt);
        } else {
          value = deser.deserialize(p, ctxt);
        }
        if (ix >= chunk.length) {
          chunk = buffer.appendCompletedChunk(chunk);
          ix = 0;
        }
        chunk[ix++] = value;
      }
    } catch (Exception e) {
      // note: pass String.class, not String[].class, as we need element type for error info
      throw JsonMappingException.wrapWithPath(e, String.class, ix);
    }
    String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
    ctxt.returnObjectBuffer(buffer);
    return result;
  }
Пример #12
0
 protected static JsonToken _initForReading(JsonParser jp)
     throws IOException, JsonParseException, JsonMappingException {
   /* First: must point to a token; if not pointing to one, advance.
    * This occurs before first read from JsonParser, as well as
    * after clearing of current token.
    */
   JsonToken t = jp.getCurrentToken();
   if (t == null) { // and then we must get something...
     t = jp.nextToken();
     if (t == null) { // [JACKSON-99] Should throw EOFException?
       throw new EOFException("No content to map to Object due to end of input");
     }
   }
   return t;
 }
  @Override
  public String[] deserialize(JsonParser p, DeserializationContext ctxt, String[] intoValue)
      throws IOException {
    // Ok: must point to START_ARRAY (or equivalent)
    if (!p.isExpectedStartArrayToken()) {
      String[] arr = handleNonArray(p, ctxt);
      if (arr == null) {
        return intoValue;
      }
      final int offset = intoValue.length;
      String[] result = new String[offset + arr.length];
      System.arraycopy(intoValue, 0, result, 0, offset);
      System.arraycopy(arr, 0, result, offset, arr.length);
      return result;
    }

    if (_elementDeserializer != null) {
      return _deserializeCustom(p, ctxt, intoValue);
    }
    final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
    int ix = intoValue.length;
    Object[] chunk = buffer.resetAndStart(intoValue, ix);

    try {
      while (true) {
        String value = p.nextTextValue();
        if (value == null) {
          JsonToken t = p.getCurrentToken();
          if (t == JsonToken.END_ARRAY) {
            break;
          }
          if (t != JsonToken.VALUE_NULL) {
            value = _parseString(p, ctxt);
          }
        }
        if (ix >= chunk.length) {
          chunk = buffer.appendCompletedChunk(chunk);
          ix = 0;
        }
        chunk[ix++] = value;
      }
    } catch (Exception e) {
      throw JsonMappingException.wrapWithPath(e, chunk, buffer.bufferedSize() + ix);
    }
    String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
    ctxt.returnObjectBuffer(buffer);
    return result;
  }
Пример #14
0
 @SuppressWarnings("unchecked")
 @Override
 public T deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   JsonToken t = jp.getCurrentToken();
   if (t == JsonToken.VALUE_NUMBER_INT) {
     return (T) new DateTime(jp.getLongValue(), DateTimeZone.UTC);
   }
   if (t == JsonToken.VALUE_STRING) {
     String str = jp.getText().trim();
     if (str.length() == 0) { // [JACKSON-360]
       return null;
     }
     return (T) new DateTime(str, DateTimeZone.UTC);
   }
   throw ctxt.mappingException(getValueClass());
 }
  /**
   * Helper method called when current token is no START_ARRAY. Will either throw an exception, or
   * try to handle value as if member of implicit array, depending on configuration.
   */
  private final Collection<String> handleNonArray(
      JsonParser jp, DeserializationContext ctxt, Collection<String> result) throws IOException {
    // [JACKSON-526]: implicit arrays from single values?
    if (!ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
      throw ctxt.mappingException(_collectionType.getRawClass());
    }
    // Strings are one of "native" (intrinsic) types, so there's never type deserializer involved
    JsonDeserializer<String> valueDes = _valueDeserializer;
    JsonToken t = jp.getCurrentToken();

    String value;

    if (t == JsonToken.VALUE_NULL) {
      value = (valueDes == null) ? null : valueDes.getNullValue();
    } else {
      value = (valueDes == null) ? _parseString(jp, ctxt) : valueDes.deserialize(jp, ctxt);
    }
    result.add(value);
    return result;
  }
Пример #16
0
 private void initializeParser(JsonParser paramJsonParser) throws IOException {
   boolean bool = true;
   if (wrapperKeys.isEmpty()) ;
   while (true) {
     return;
     try {
       if ((paramJsonParser.skipToKey(wrapperKeys) != null)
           && (paramJsonParser.getCurrentToken() != JsonToken.END_OBJECT)) ;
       while (true) {
         Preconditions.checkArgument(
             bool, "wrapper key(s) not found: %s", new Object[] {wrapperKeys});
         if (0 == 0) break;
         paramJsonParser.close();
         return;
         bool = false;
       }
     } finally {
       if (1 != 0) paramJsonParser.close();
     }
   }
 }
  private Object success(Class<?> clazz, HttpInputMessage inputMessage)
      throws JsonParseException, IOException {

    // Note, parsing code used from ektorp project
    JsonParser jp = objectMapper.getJsonFactory().createJsonParser(inputMessage.getBody());
    if (jp.nextToken() != JsonToken.START_OBJECT) {
      throw new RuntimeException("Expected data to start with an Object");
    }
    Map<String, Integer> fields = readHeaderFields(jp);

    List result;
    if (fields.containsKey(TOTAL_ROWS_FIELD_NAME)) {
      int totalRows = fields.get(TOTAL_ROWS_FIELD_NAME);
      if (totalRows == 0) {
        return Collections.emptyList();
      }
      result = new ArrayList(totalRows);
    } else {
      result = new ArrayList();
    }

    ParseState state = new ParseState();

    Object first = parseFirstRow(jp, state, clazz);
    if (first == null) {
      return Collections.emptyList();
    } else {
      result.add(first);
    }

    while (jp.getCurrentToken() != null) {
      skipToField(jp, state.docFieldName, state);
      if (atEndOfRows(jp)) {
        return result;
      }
      result.add(jp.readValueAs(clazz));
      endRow(jp, state);
    }
    return result;
  }
  protected MediaContent readMediaContent(JsonParser parser) throws IOException {
    MediaContent mc = new MediaContent();
    if (parser.nextToken() != JsonToken.START_OBJECT) {
      reportIllegal(parser, JsonToken.START_OBJECT);
    }
    // first fast version when field-order is as expected
    if (parser.nextFieldName(FIELD_MEDIA)) {
      mc.media = readMedia(parser);
      if (parser.nextFieldName(FIELD_IMAGES)) {
        mc.images = readImages(parser);
        parser.nextToken();
        verifyCurrent(parser, JsonToken.END_OBJECT);
        return mc;
      }
    }

    // and fallback if order was changed
    for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) {
      String field = parser.getCurrentName();
      Integer I = fullFieldToIndex.get(field);
      if (I != null) {
        switch (I) {
          case FIELD_IX_MEDIA:
            mc.media = readMedia(parser);
            continue;
          case FIELD_IX_IMAGES:
            mc.images = readImages(parser);
            continue;
        }
      }
      throw new IllegalStateException("Unexpected field '" + field + "'");
    }
    verifyCurrent(parser, JsonToken.END_OBJECT);

    if (mc.media == null) throw new IllegalStateException("Missing field: " + FIELD_MEDIA);
    if (mc.images == null) mc.images = new ArrayList<Image>();

    return mc;
  }
  /**
   * Method that gets textual contents of the current token using available methods, and ensures
   * results are consistent, before returning them
   */
  protected String getAndVerifyText(JsonParser jp) throws IOException, JsonParseException {
    // Ok, let's verify other accessors
    int actLen = jp.getTextLength();
    char[] ch = jp.getTextCharacters();
    String str2 = new String(ch, jp.getTextOffset(), actLen);
    String str = jp.getText();

    if (str.length() != actLen) {
      fail(
          "Internal problem (jp.token == "
              + jp.getCurrentToken()
              + "): jp.getText().length() ['"
              + str
              + "'] == "
              + str.length()
              + "; jp.getTextLength() == "
              + actLen);
    }
    assertEquals("String access via getText(), getTextXxx() must be the same", str, str2);

    return str;
  }
  @Override
  public Enum<?> deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
    JsonToken curr = jp.getCurrentToken();

    // Usually should just get string value:
    if (curr == JsonToken.VALUE_STRING || curr == JsonToken.FIELD_NAME) {
      String name = jp.getText();
      Enum<?> result = _resolver.findEnum(name);
      if (result == null
          && !ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
        throw ctxt.weirdStringException(
            name, _resolver.getEnumClass(), "value not one of declared Enum instance names");
      }
      return result;
    }
    // But let's consider int acceptable as well (if within ordinal range)
    if (curr == JsonToken.VALUE_NUMBER_INT) {
      /* ... unless told not to do that. :-)
       * (as per [JACKSON-412]
       */
      if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)) {
        throw ctxt.mappingException(
            "Not allowed to deserialize Enum value out of JSON number (disable DeserializationConfig.DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS to allow)");
      }

      int index = jp.getIntValue();
      Enum<?> result = _resolver.getEnum(index);
      if (result == null
          && !ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
        throw ctxt.weirdNumberException(
            Integer.valueOf(index),
            _resolver.getEnumClass(),
            "index value outside legal index range [0.." + _resolver.lastValidIndex() + "]");
      }
      return result;
    }
    throw ctxt.mappingException(_resolver.getEnumClass());
  }
Пример #21
0
  public ArtistImpl(JsonParser parser) throws JsonParseException, IOException {
    if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
      if (parser.getCurrentToken() == JsonToken.VALUE_NULL) return;
      throw new IOException(
          "Expected data to start with an Object. Found " + parser.getCurrentToken());
    }

    while (parser.nextToken() != JsonToken.END_OBJECT) {
      String fName = parser.getCurrentName();
      parser.nextToken();

      if (fName.equals("id")) id = parser.getLongValue();
      else if (fName.equals("name")) name = parser.getText();
      else if (fName.equals("eventDescription")) description = parser.getText();
      else if (fName.equals("urlOfficialWebsite")) siteUrl = JFlyUtils.parseURL(parser.getText());
      else if (fName.equals("urlMySpace")) myspaceUrl = JFlyUtils.parseURL(parser.getText());
      else if (fName.equals("urlFacebook")) facebookUrl = JFlyUtils.parseURL(parser.getText());
      else if (fName.equals("twitterScreenName")) twitterScreenName = parser.getText();
      else if (fName.equals("urlAudio")) audioUrl = JFlyUtils.parseURL(parser.getText());
      else if (fName.equals("urlPurchaseMusic")) purchaseUrl = JFlyUtils.parseURL(parser.getText());
      else if (fName.equals("embedAudio")) audioHtml = parser.getText();
      else if (fName.equals("embedVideo")) videoHtml = parser.getText();
      else if (fName.equals("idMobileFriendly")) mobileFriendly = parser.getBooleanValue();
      else if (fName.equals("images")) {
        if (parser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
          while (parser.nextToken() != JsonToken.END_ARRAY) {
            images.add(new ImageMetaImpl(parser));
          }
        }
      } else if (fName.equals("youtubeVideos")) {
        if (parser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
          while (parser.nextToken() != JsonToken.END_ARRAY) {
            youTubeVideos.add(new YouTubeMetaImpl(parser));
          }
        }
      } else if (parser.getCurrentToken() == JsonToken.START_OBJECT
          || parser.getCurrentToken() == JsonToken.START_ARRAY) {
        parser.skipChildren();
      }
    } // end while
  }
Пример #22
0
 @Override
 public String deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   // 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
   String text = jp.getValueAsString();
   if (text != null) {
     return text;
   }
   // [JACKSON-330]: need to gracefully handle byte[] data, as base64
   JsonToken curr = jp.getCurrentToken();
   if (curr == JsonToken.VALUE_EMBEDDED_OBJECT) {
     Object ob = jp.getEmbeddedObject();
     if (ob == null) {
       return null;
     }
     if (ob instanceof byte[]) {
       return Base64Variants.getDefaultVariant().encode((byte[]) ob, false);
     }
     // otherwise, try conversion using toString()...
     return ob.toString();
   }
   throw ctxt.mappingException(_valueClass, curr);
 }
 @Override
 public OffsetTime deserialize(JsonParser parser, DeserializationContext context)
     throws IOException {
   if (parser.hasToken(JsonToken.VALUE_STRING)) {
     String string = parser.getText().trim();
     if (string.length() == 0) {
       return null;
     }
     try {
       return OffsetTime.parse(string, _formatter);
     } catch (DateTimeException e) {
       _rethrowDateTimeException(parser, context, e, string);
     }
   }
   if (!parser.isExpectedStartArrayToken()) {
     if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
       return (OffsetTime) parser.getEmbeddedObject();
     }
     throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
   }
   int hour = parser.nextIntValue(-1);
   if (hour == -1) {
     JsonToken t = parser.getCurrentToken();
     if (t == JsonToken.END_ARRAY) {
       return null;
     }
     if (t != JsonToken.VALUE_NUMBER_INT) {
       _reportWrongToken(parser, context, JsonToken.VALUE_NUMBER_INT, "hours");
     }
     hour = parser.getIntValue();
   }
   int minute = parser.nextIntValue(-1);
   if (minute == -1) {
     JsonToken t = parser.getCurrentToken();
     if (t == JsonToken.END_ARRAY) {
       return null;
     }
     if (t != JsonToken.VALUE_NUMBER_INT) {
       _reportWrongToken(parser, context, JsonToken.VALUE_NUMBER_INT, "minutes");
     }
     minute = parser.getIntValue();
   }
   int partialSecond = 0;
   int second = 0;
   if (parser.nextToken() == JsonToken.VALUE_NUMBER_INT) {
     second = parser.getIntValue();
     if (parser.nextToken() == JsonToken.VALUE_NUMBER_INT) {
       partialSecond = parser.getIntValue();
       if (partialSecond < 1_000
           && !context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
         partialSecond *= 1_000_000; // value is milliseconds, convert it to nanoseconds
       }
       parser.nextToken();
     }
   }
   if (parser.getCurrentToken() == JsonToken.VALUE_STRING) {
     OffsetTime t =
         OffsetTime.of(hour, minute, second, partialSecond, ZoneOffset.of(parser.getText()));
     if (parser.nextToken() != JsonToken.END_ARRAY) {
       _reportWrongToken(parser, context, JsonToken.END_ARRAY, "timezone");
     }
     return t;
   }
   throw context.wrongTokenException(
       parser, JsonToken.VALUE_STRING, "Expected string for TimeZone after numeric values");
 }
 private boolean isEndOfRow(JsonParser jp) {
   return jp.getCurrentToken() == JsonToken.END_OBJECT;
 }
 private boolean atObjectStart(JsonParser jp) {
   return jp.getCurrentToken() == JsonToken.START_OBJECT;
 }
 private boolean atEndOfRows(JsonParser jp) {
   return jp.getCurrentToken() != JsonToken.START_OBJECT;
 }
 protected void assertToken(JsonToken expToken, JsonParser jp) {
   assertToken(expToken, jp.getCurrentToken());
 }
  private Media readMedia(JsonParser parser) throws IOException {
    if (parser.nextToken() != JsonToken.START_OBJECT) {
      reportIllegal(parser, JsonToken.START_OBJECT);
    }
    Media media = new Media();
    boolean haveWidth = false;
    boolean haveHeight = false;
    boolean haveDuration = false;
    boolean haveSize = false;

    // As with above, first fast path
    if (parser.nextFieldName(FIELD_PLAYER)) {
      media.player = Media.Player.find(parser.nextTextValue());
      if (parser.nextFieldName(FIELD_URI)) {
        media.uri = parser.nextTextValue();
        if (parser.nextFieldName(FIELD_TITLE)) {
          media.title = parser.nextTextValue();
          if (parser.nextFieldName(FIELD_WIDTH)) {
            haveWidth = true;
            media.width = parser.nextIntValue(-1);
            if (parser.nextFieldName(FIELD_HEIGHT)) {
              haveHeight = true;
              media.height = parser.nextIntValue(-1);
              if (parser.nextFieldName(FIELD_FORMAT)) {
                media.format = parser.nextTextValue();
                if (parser.nextFieldName(FIELD_DURATION)) {
                  haveDuration = true;
                  media.duration = parser.nextLongValue(-1L);
                  if (parser.nextFieldName(FIELD_SIZE)) {
                    haveSize = true;
                    media.size = parser.nextLongValue(-1L);
                    if (parser.nextFieldName(FIELD_BITRATE)) {
                      media.bitrate = parser.nextIntValue(-1);
                      media.hasBitrate = true;
                      if (parser.nextFieldName(FIELD_COPYRIGHT)) {
                        media.copyright = parser.nextTextValue();
                        if (parser.nextFieldName(FIELD_PERSONS)) {
                          media.persons = readPersons(parser);
                          parser.nextToken();
                          verifyCurrent(parser, JsonToken.END_OBJECT);
                          return media;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    // and if something reorder or missing, general loop:

    for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) {
      String field = parser.getCurrentName();
      Integer I = fullFieldToIndex.get(field);
      if (I != null) {
        switch (I) {
          case FIELD_IX_PLAYER:
            media.player = Media.Player.find(parser.nextTextValue());
            continue;
          case FIELD_IX_URI:
            media.uri = parser.nextTextValue();
            continue;
          case FIELD_IX_TITLE:
            media.title = parser.nextTextValue();
            continue;
          case FIELD_IX_WIDTH:
            media.width = parser.nextIntValue(-1);
            haveWidth = true;
            continue;
          case FIELD_IX_HEIGHT:
            media.height = parser.nextIntValue(-1);
            haveHeight = true;
            continue;
          case FIELD_IX_FORMAT:
            media.format = parser.nextTextValue();
            continue;
          case FIELD_IX_DURATION:
            media.duration = parser.nextLongValue(-1L);
            haveDuration = true;
            continue;
          case FIELD_IX_SIZE:
            media.size = parser.nextLongValue(-1L);
            haveSize = true;
            continue;
          case FIELD_IX_BITRATE:
            media.bitrate = parser.nextIntValue(-1);
            media.hasBitrate = true;
            continue;
          case FIELD_IX_PERSONS:
            media.persons = readPersons(parser);
            continue;
          case FIELD_IX_COPYRIGHT:
            media.copyright = parser.nextTextValue();
            continue;
        }
      }
      throw new IllegalStateException("Unexpected field '" + field + "'");
    }
    verifyCurrent(parser, JsonToken.END_OBJECT);

    if (media.uri == null) throw new IllegalStateException("Missing field: " + FIELD_URI);
    if (!haveWidth) throw new IllegalStateException("Missing field: " + FIELD_WIDTH);
    if (!haveHeight) throw new IllegalStateException("Missing field: " + FIELD_HEIGHT);
    if (media.format == null) throw new IllegalStateException("Missing field: " + FIELD_FORMAT);
    if (!haveDuration) throw new IllegalStateException("Missing field: " + FIELD_DURATION);
    if (!haveSize) throw new IllegalStateException("Missing field: " + FIELD_SIZE);
    if (media.persons == null) media.persons = new ArrayList<String>();
    if (media.player == null) throw new IllegalStateException("Missing field: " + FIELD_PLAYER);

    return media;
  }
  private Image readImage(JsonParser parser) throws IOException {
    boolean haveWidth = false;
    boolean haveHeight = false;
    Image image = new Image();
    if (parser.nextFieldName(FIELD_URI)) {
      image.uri = parser.nextTextValue();
      if (parser.nextFieldName(FIELD_TITLE)) {
        image.title = parser.nextTextValue();
        if (parser.nextFieldName(FIELD_WIDTH)) {
          image.width = parser.nextIntValue(-1);
          haveWidth = true;
          if (parser.nextFieldName(FIELD_HEIGHT)) {
            image.height = parser.nextIntValue(-1);
            haveHeight = true;
            if (parser.nextFieldName(FIELD_SIZE)) {
              image.size = Image.Size.valueOf(parser.nextTextValue());
              parser.nextToken();
              verifyCurrent(parser, JsonToken.END_OBJECT);
              return image;
            }
          }
        }
      }
    }

    for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) {
      String field = parser.getCurrentName();
      // read value token (or START_ARRAY)
      parser.nextToken();
      Integer I = fullFieldToIndex.get(field);
      if (I != null) {
        switch (I) {
          case FIELD_IX_URI:
            image.uri = parser.getText();
            continue;
          case FIELD_IX_TITLE:
            image.title = parser.getText();
            continue;
          case FIELD_IX_WIDTH:
            image.width = parser.getIntValue();
            haveWidth = true;
            continue;
          case FIELD_IX_HEIGHT:
            image.height = parser.getIntValue();
            haveHeight = true;
            continue;
          case FIELD_IX_SIZE:
            image.size = Image.Size.valueOf(parser.getText());
            continue;
        }
      }
      throw new IllegalStateException("Unexpected field '" + field + "'");
    }

    if (image.uri == null) throw new IllegalStateException("Missing field: " + FIELD_URI);
    if (!haveWidth) throw new IllegalStateException("Missing field: " + FIELD_WIDTH);
    if (!haveHeight) throw new IllegalStateException("Missing field: " + FIELD_HEIGHT);
    if (image.size == null) throw new IllegalStateException("Missing field: " + FIELD_SIZE);

    verifyCurrent(parser, JsonToken.END_OBJECT);

    return image;
  }
 private final void verifyCurrent(JsonParser parser, JsonToken expToken) throws IOException {
   if (parser.getCurrentToken() != expToken) {
     reportIllegal(parser, expToken);
   }
 }