Джексон десериализует целочисленную ошибку преобразования - PullRequest
0 голосов
/ 22 октября 2018

Я пытаюсь обработать, если обязательное поле содержит значение String, а я ожидаю его как Integer.Например;

{
"transactionTimeMilliseconds": "asd"
}

, но в коде Java оно определено как int.

private int transactionTimeMilliseconds;
@JsonCreator
public Channel(@JsonProperty("transactionTimeMilliseconds") int transactionTimeMilliseconds) { 
        this.transactionTimeMilliseconds = transactionTimeMilliseconds;
    }

У меня есть класс информера исключения.

CLASS

@ControllerAdvice
public class ExceptionConfiguration extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MismatchedInputException.class) // Or whatever exception type you want to handle
    public ResponseEntity<JsonException> handleMissingFieldError(MismatchedInputException exception) { // Or whatever exception type you want to handle
        int code = 601;
        String message = exception.getMessage().split("\n")[0] + exception.getMessage().split(";")[1].replace("]", "");
        JsonException jsonException = new JsonException(code,message);
        return ResponseEntity.status(jsonException.getCode()).body(jsonException);
    }

    @ExceptionHandler(UnrecognizedPropertyException.class) // Or whatever exception type you want to handle
    public ResponseEntity<JsonException> handleUnrecognizedFieldError(UnrecognizedPropertyException exception) { // Or whatever exception type you want to handle
        int code = 602;
        String message = exception.getMessage().split(",")[0] + exception.getMessage().split(";")[1].replace("]", "");
        JsonException jsonException = new JsonException(code,message);
        return ResponseEntity.status(jsonException.getCode()).body(jsonException);
    }

    @ExceptionHandler(JsonParseException.class) // Or whatever exception type you want to handle
    public ResponseEntity<JsonException> handleJsonParseError(JsonParseException exception) {
        int code = 603;
        String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
        JsonException jsonException = new JsonException(code,message);
        return ResponseEntity.status(jsonException.getCode()).body(jsonException);
    }

    @ExceptionHandler(InvalidFormatException.class) // Or whatever exception type you want to handle
    public ResponseEntity<JsonException> handleJsonInvalidFormatError(InvalidFormatException exception) {
        int code = 604;
        String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
        JsonException jsonException = new JsonException(code,message);
        return ResponseEntity.status(jsonException.getCode()).body(jsonException);
    }

    @ExceptionHandler(JsonMappingException.class) // Or whatever exception type you want to handle
    public ResponseEntity<JsonException> handleNullFieldError(JsonMappingException exception) {
        int code = 605;
        String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
        JsonException jsonException = new JsonException(code,message);
        return ResponseEntity.status(jsonException.getCode()).body(jsonException);
    }
}

Я должен распознать это значение, и если это поле неверно, как написано выше, установите его значение по умолчанию как 0.

Должен ли я писатьпользовательский десериализатор для решения этой проблемы?Спасибо.

1 Ответ

0 голосов
/ 22 октября 2018

что-то вроде этого у меня сработало:

class Val {
    private int v;

    public int getV() {
        return v;
    }

    @JsonSetter // or  @JsonProperty("v")
    public void setV(String v) {
        System.out.println("in setter");
        try {
           this.v = Integer.parseInt(v);
        } catch (Exception e) {
            this.v = 0;
        }
    }
}

Тест:

@Test
public void test() throws IOException {
    String json = " { \"v\" : 1 } ";
    Val v = new ObjectMapper().readValue(json, Val.class);
    System.out.println(v.getV()); // prints 1

    json = " { \"v\" : \"asd\" } ";
    v = new ObjectMapper().readValue(json, Val.class);
    System.out.println(v.getV()); // prints 0
}

Я попробовал что-то подобное, но пока не смог заставить его работать.

class Val {
    private int v;

    @JsonCreator
    public Val(@JsonProperty("v") String v) {
        System.out.println("in setter");
        try {
           this.v = Integer.parseInt(v);
        } catch (Exception e) {
            this.v = 0;
        }
    }

    public int getV() {
        return v;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...