类com.fasterxml.jackson.databind.exc.MismatchedInputException源码实例Demo

下面列出了怎么用com.fasterxml.jackson.databind.exc.MismatchedInputException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sdk-java   文件: CloudEventDeserializer.java
@Override
public CloudEvent deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    // In future we could eventually find a better solution avoiding this buffering step, but now this is the best option
    // Other sdk does the same in order to support all versions
    ObjectNode node = ctxt.readValue(p, ObjectNode.class);

    try {
        return new JsonMessage(p, node).read(CloudEventBuilder::fromSpecVersion);
    } catch (RuntimeException e) {
        // Yeah this is bad but it's needed to support checked exceptions...
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        throw MismatchedInputException.wrapWithPath(e, null);
    }
}
 
源代码2 项目: lams   文件: ObjectMapper.java
/**
 * Method called to ensure that given parser is ready for reading
 * content for data binding.
 *
 * @return First token to be used for data binding after this call:
 *  can never be null as exception will be thrown if parser cannot
 *  provide more tokens.
 *
 * @throws IOException if the underlying input source has problems during
 *   parsing
 * @throws JsonParseException if parser has problems parsing content
 * @throws JsonMappingException if the parser does not have any more
 *   content to map (note: Json "null" value is considered content;
 *   enf-of-stream not)
 */
protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException
{
    _deserializationConfig.initialize(p); // since 2.5

    // 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 = p.getCurrentToken();
    if (t == null) {
        // and then we must get something...
        t = p.nextToken();
        if (t == null) {
            // Throw mapping exception, since it's failure to map,
            //   not an actual parsing problem
            throw MismatchedInputException.from(p, targetType,
                    "No content to map due to end-of-input");
        }
    }
    return t;
}
 
源代码3 项目: jackson-modules-java8   文件: ZoneIdDeserTest.java
public void testStrictDeserializeFromEmptyString() throws Exception {

        final String key = "zoneId";
        final ObjectMapper mapper = mapperBuilder()
                .withCoercionConfig(LogicalType.DateTime,
                        cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
                .build();
        final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

        String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
        Map<String, ZoneId> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
        assertNull(actualMapFromNullStr.get(key));

        String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
        try {
            objectReader.readValue(valueFromEmptyStr);
            fail("Should not pass");
        } catch (MismatchedInputException e) {
            verifyException(e, "Cannot coerce empty String");
            verifyException(e, ZoneId.class.getName());
        }
    }
 
源代码4 项目: jackson-modules-java8   文件: ZoneIdDeserTest.java
@Test
public void testZoneIdDeserFromEmpty() throws Exception
{
    // by default, should be fine
    assertNull(MAPPER.readValue(quote("  "), ZoneId.class));
    // but fail if coercion illegal
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    try {
        mapper.readValue(quote(" "), ZoneId.class);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneId.class.getName());
    }
}
 
源代码5 项目: jackson-modules-java8   文件: PeriodDeserTest.java
@Test
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "period";
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, Period> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    try {
        objectReader.readValue(valueFromEmptyStr);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
    }
}
 
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "datetime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalDateTime.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false))
            )
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, LocalDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    // TODO: nothing stops us from writing an empty string, maybe there should be a check there too?
    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", dateValAsEmptyStr));
    // with strict, deserializing an empty string is not permitted
    objectReader.readValue(valueFromEmptyStr);
}
 
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "localTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalTime.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, LocalTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
源代码8 项目: jackson-modules-java8   文件: InstantDeserTest.java
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "instant";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(Instant.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, Instant> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "zonedDateTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(ZonedDateTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
        .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, ZonedDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
源代码10 项目: jackson-modules-java8   文件: DurationDeserTest.java
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "duration";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(Duration.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, Duration> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, dateValAsEmptyStr));
    objectReader.readValue(valueFromEmptyStr);
}
 
源代码11 项目: jackson-modules-java8   文件: LocalDateDeserTest.java
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "date";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalDate.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false))
            )
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, LocalDate> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    // TODO: nothing stops us from writing an empty string, maybe there should be a check there too?
    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", dateValAsEmptyStr));
    // with strict, deserializing an empty string is not permitted
    objectReader.readValue(valueFromEmptyStr);
}
 
源代码12 项目: jackson-modules-java8   文件: YearMonthDeserTest.java
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "YearMonth";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(YearMonth.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, YearMonth> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
@Test
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "zoneOffset";
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, ZoneOffset> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    try {
        objectReader.readValue(valueFromEmptyStr);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneOffset.class.getName());
    }
}
 
@Test
public void testZoneOffsetDeserFromEmpty() throws Exception
{
    // by default, should be fine
    assertNull(MAPPER.readValue(quote("  "), ZoneOffset.class));
    // but fail if coercion illegal
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    try {
        mapper.readerFor(ZoneOffset.class)
            .readValue(quote(" "));
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneOffset.class.getName());
    }
}
 
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "OffsetDateTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(OffsetDateTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
        .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, OffsetDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "OffsetTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(OffsetTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, OffsetTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
源代码17 项目: sdk-java   文件: CloudEventDeserializer.java
private String getStringNode(ObjectNode objNode, JsonParser p, String attributeName) throws JsonProcessingException {
    String val = getOptionalStringNode(objNode, p, attributeName);
    if (val == null) {
        throw MismatchedInputException.from(p, CloudEvent.class, "Missing mandatory " + attributeName + " attribute");
    }
    return val;
}
 
源代码18 项目: sdk-java   文件: CloudEventDeserializer.java
private void assertNodeType(JsonNode node, JsonNodeType type, String attributeName, String desc) throws JsonProcessingException {
    if (node.getNodeType() != type) {
        throw MismatchedInputException.from(
            p,
            CloudEvent.class,
            "Wrong type " + node.getNodeType() + " for attribute " + attributeName + ", expecting " + type + (desc != null ? ". " + desc : "")
        );
    }
}
 
@Test
public void testCreateNoNameDictionary() throws Exception {
    exception.expect(EPSCommonException.class);
    exception.expectMessage("Wrong input format");
    exception.expectCause(new CauseMatcher(MismatchedInputException.class, "Missing required creator property 'name' (index 0)\n at [Source: (FileInputStream); line: 13, column: 1]"));

    loadDictionaryFrom("noNameDictionary.json");
}
 
/**
 * 处理非法输入异常
 *
 * @param mismatchedInputException 非法输入异常的详细内容
 * @return 返回异常信息
 */
@ExceptionHandler(MismatchedInputException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ExceptionResult handlerMismatchedInputException(
        MismatchedInputException mismatchedInputException) {
    ExceptionResult ex = new ExceptionResult();
    ex.setCode(400);
    ex.setMsg("非法输入");
    return ex;
}
 
源代码21 项目: act-platform   文件: MismatchedInputMapper.java
@Override
public Response toResponse(MismatchedInputException ex) {
  return ResultStash.builder()
          .setStatus(Response.Status.PRECONDITION_FAILED)
          .addFieldError("JSON field has an invalid type.", "invalid.json.field.type", MapperUtils.printPropertyPath(ex), "")
          .buildResponse();
}
 
@Test
public void testdecodeResponseNull() throws Exception {
  JavaType resultType = TypeFactory.unknownType();
  Object result = pp.decodeResponse(Buffer.buffer(), resultType);
  Assert.assertNull(result);

  ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {});
  try {
    pp.decodeResponse(is, resultType);
    Assert.fail();
  } catch (Exception e) {
    Assert.assertTrue(e instanceof MismatchedInputException);
  }
}
 
源代码23 项目: servicecomb-java-chassis   文件: TestDoSFix.java
@Test
public void testChar() {
  batFastFail(char.class, InputCoercionException.class, MismatchedInputException.class);
  batFastFail(Character.class, InputCoercionException.class, MismatchedInputException.class);

  batFastFail("cValue", JsonMappingException.class, MismatchedInputException.class);
  batFastFail("cObjValue", JsonMappingException.class, MismatchedInputException.class);
}
 
源代码24 项目: lams   文件: DeserializationContext.java
/**
 * Helper method used to indicate a problem with input in cases where more
 * specific <code>reportXxx()</code> method was not available.
 *
 * @since 2.9
 */
public <T> T reportInputMismatch(BeanProperty prop,
        String msg, Object... msgArgs) throws JsonMappingException
{
    msg = _format(msg, msgArgs);
    JavaType type = (prop == null) ? null : prop.getType();
    throw MismatchedInputException.from(getParser(), type, msg);
}
 
源代码25 项目: lams   文件: DeserializationContext.java
/**
 * Helper method used to indicate a problem with input in cases where more
 * specific <code>reportXxx()</code> method was not available.
 *
 * @since 2.9
 */
public <T> T reportInputMismatch(JsonDeserializer<?> src,
        String msg, Object... msgArgs) throws JsonMappingException
{
    msg = _format(msg, msgArgs);
    throw MismatchedInputException.from(getParser(), src.handledType(), msg);
}
 
源代码26 项目: lams   文件: DeserializationContext.java
/**
 * Helper method used to indicate a problem with input in cases where more
 * specific <code>reportXxx()</code> method was not available.
 *
 * @since 2.9
 */
public <T> T reportInputMismatch(Class<?> targetType,
        String msg, Object... msgArgs) throws JsonMappingException
{
    msg = _format(msg, msgArgs);
    throw MismatchedInputException.from(getParser(), targetType, msg);
}
 
源代码27 项目: lams   文件: DeserializationContext.java
/**
 * Helper method used to indicate a problem with input in cases where more
 * specific <code>reportXxx()</code> method was not available.
 *
 * @since 2.9
 */
public <T> T reportInputMismatch(JavaType targetType,
        String msg, Object... msgArgs) throws JsonMappingException
{
    msg = _format(msg, msgArgs);
    throw MismatchedInputException.from(getParser(), targetType, msg);
}
 
源代码28 项目: lams   文件: DeserializationContext.java
public <T> T reportTrailingTokens(Class<?> targetType,
            JsonParser p, JsonToken trailingToken) throws JsonMappingException
    {
        throw MismatchedInputException.from(p, targetType, String.format(
"Trailing token (of type %s) found after value (bound as %s): not allowed as per `DeserializationFeature.FAIL_ON_TRAILING_TOKENS`",
trailingToken, ClassUtil.nameOf(targetType)
                ));
    }
 
源代码29 项目: lams   文件: DeserializationContext.java
public JsonMappingException wrongTokenException(JsonParser p, Class<?> targetType,
        JsonToken expToken, String extra)
{
    String msg = String.format("Unexpected token (%s), expected %s",
            p.getCurrentToken(), expToken);
    msg = _colonConcat(msg, extra);
    return MismatchedInputException.from(p, targetType, msg);
}
 
源代码30 项目: lams   文件: DeserializationContext.java
/**
 * @since 2.5
 *
 * @deprecated Since 2.8 use {@link #handleUnknownTypeId} instead
 */
@Deprecated
public JsonMappingException unknownTypeException(JavaType type, String id,
        String extraDesc)
{
    String msg = String.format("Could not resolve type id '%s' into a subtype of %s",
            id, type);
    msg = _colonConcat(msg, extraDesc);
    return MismatchedInputException.from(_parser, type, msg);
}
 
 类方法
 同包方法