Главная » Ошибки » Jackson Exceptions

Jackson Exceptions

В этой статье

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll go over the most common Jackson Exceptions — JsonMappingException and UnrecognizedPropertyException.

Finally, we’ll briefly discuss Jackson “No such method” errors.

Further reading:

Как сортировать по разным полям?

  • 1 подписчик
  • вчера
  • 55 просмотров

ответ
1

  • java
    • Java

    • +1 ещё

    Простой

  • Jackson – Custom Serializer

    Control your JSON output with Jackson 2 by using a Custom Serializer. Read more →

    Как осуществить переход из одного switch-case в другой и вернуться обратно?

    • 1 подписчик
    • 16 часов назад
    • 57 просмотров

    ответа
    2

  • mysql
    • MySQL

    • +2 ещё

    Простой

  • Jackson Annotation Examples

    The core of Jackson is basically a set of annotations – make sure you understand these well. Read more →

    Как инициализировать поля из интерфейса?

    • 1 подписчик
    • час назад
    • 23 просмотра

    ответ
    1

  • api
    • API

    • +2 ещё

    Простой

  • Getting Started with Custom Deserialization in Jackson

    Use Jackson to map custom JSON to any java entity graph with full control over the deserialization process. Read more →

    Как отобразить картинку на сайте из MySQL используя Spring?

    • 1 подписчик
    • 23 часа назад
    • 66 просмотров

    ответа
    2

  • android
    • Android

    • +3 ещё

    Средний

  • Preview 0

    Existing Members

    Sign in to your account

    2. JsonMappingException: Can Not Construct Instance Of

    2.1. The Problem

    First, let’s take a look at JsonMappingException: Can Not Construct Instance Of.

    This exception is thrown if Jackson can’t create an instance of the class, which happens if the class is abstract or it is just an interface.

    Here we’ll try to deserialize an instance from class Zoo that has a property animal with abstract type Animal:

    public class Zoo {
    public Animal animal;

    public Zoo() { }
    }

    abstract class Animal {
    public String name;

    public Animal() { }
    }

    class Cat extends Animal {
    public int lives;

    public Cat() { }
    }

    When we try to deserialize a JSON String to Zoo instance, it throws the JsonMappingException: Can Not Construct Instance Of:

    @Test(expected = JsonMappingException.class)
    public void givenAbstractClass_whenDeserializing_thenException()
    throws IOException {
    String json = “{“animal”:{“name”:”lacy”}}”;
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader().forType(Zoo.class).readValue(json);
    }

    This is the full exception:

    com.fasterxml.jackson.databind.JsonMappingException:
    Can not construct instance of org.baeldung.jackson.exception.Animal,
    problem: abstract types either need to be mapped to concrete types,
    have custom deserializer,
    or be instantiated with additional type information
    at
    [Source: {“animal”:{“name”:”lacy”}}; line: 1, column: 2] (through reference chain: org.baeldung.jackson.exception.Zoo[“animal”])
    at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

    2.2. Solutions

    We can solve the problem with a simple annotation — @JsonDeserialize on the abstract class:

    @JsonDeserialize(as = Cat.class)
    abstract class Animal {…}

    Note that if we have more than one subtype of the abstract class, we should consider including subtype information as shown in the article Inheritance With Jackson.

    3. JsonMappingException: No Suitable Constructor

    3.1. The Problem

    Now let’s look at the common JsonMappingException: No Suitable Constructor found for type.

    This exception is thrown if Jackson can’t access the constructor.

    In the following example, class User doesn’t have a default constructor:

    public class User {
    public int id;
    public String name;

    public User(int id, String name) {
    this.id = id;
    this.name = name;
    }
    }

    When we try to deserialize a JSON String to User, JsonMappingException: No Suitable Constructor Found is thrown:

    @Test(expected = JsonMappingException.class)
    public void givenNoDefaultConstructor_whenDeserializing_thenException()
    throws IOException {
    String json = “{“id”:1,”name”:”John”}”;
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader().forType(User.class).readValue(json);
    }

    And this is the full exception:

    com.fasterxml.jackson.databind.JsonMappingException:
    No suitable constructor found for type
    [simple type, class org.baeldung.jackson.exception.User]:
    can not instantiate from JSON object (need to add/enable type information?)
    at [Source: {“id”:1,”name”:”John”}; line: 1, column: 2] at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

    3.2. The Solution

    To solve this problem, we just add a default constructor:

    public class User {
    public int id;
    public String name;

    public User() {
    super();
    }

    public User(int id, String name) {
    this.id = id;
    this.name = name;
    }
    }

    Now when we deserialize, the process will work just fine:

    @Test
    public void givenDefaultConstructor_whenDeserializing_thenCorrect()
    throws IOException {

    String json = “{“id”:1,”name”:”John”}”;
    ObjectMapper mapper = new ObjectMapper();

    User user = mapper.reader()
    .forType(User.class).readValue(json);
    assertEquals(“John”, user.name);
    }

    Не открывается action menu activity как исправить?

    • 1 подписчик
    • 23 часа назад
    • 15 просмотров

    ответов
    0

  • java
    • Java

    • +2 ещё

    Простой

  • 4. JsonMappingException: Root Name Does Not Match Expected

    4.1. The Problem

    Next, let’s take a look at JsonMappingException: Root Name Does Not Match Expected.

    This exception is thrown if the JSON doesn’t match exactly what Jackson is looking for.

    For example, the main JSON could be wrapped:

    @Test(expected = JsonMappingException.class)
    public void givenWrappedJsonString_whenDeserializing_thenException()
    throws IOException {
    String json = “{“user”:{“id”:1,”name”:”John”}}”;

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

    mapper.reader().forType(User.class).readValue(json);
    }

    This is the full exception:

    com.fasterxml.jackson.databind.JsonMappingException:
    Root name ‘user’ does not match expected (‘User’) for type
    [simple type, class org.baeldung.jackson.dtos.User] at [Source: {“user”:{“id”:1,”name”:”John”}}; line: 1, column: 2] at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

    4.2. The Solution

    We can solve this problem using the annotation @JsonRootName:

    @JsonRootName(value = “user”)
    public class UserWithRoot {
    public int id;
    public String name;
    }

    When we try to deserialize the wrapped JSON, it works correctly:

    @Test
    public void
    givenWrappedJsonStringAndConfigureClass_whenDeserializing_thenCorrect()
    throws IOException {

    String json = “{“user”:{“id”:1,”name”:”John”}}”;

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

    UserWithRoot user = mapper.reader()
    .forType(UserWithRoot.class)
    .readValue(json);
    assertEquals(“John”, user.name);
    }

    5. JsonMappingException: No Serializer Found for Class

    5.1. The Problem

    Now let’s take a look at JsonMappingException: No Serializer Found for Class.

    This exception is thrown if we try to serialize an instance while its properties and their getters are private.

    We’ll try to serialize a UserWithPrivateFields:

    public class UserWithPrivateFields {
    int id;
    String name;
    }

    When we try to serialize an instance of UserWithPrivateFields, JsonMappingException: No Serializer Found for Class is thrown:

    @Test(expected = JsonMappingException.class)
    public void givenClassWithPrivateFields_whenSerializing_thenException()
    throws IOException {
    UserWithPrivateFields user = new UserWithPrivateFields(1, “John”);

    ObjectMapper mapper = new ObjectMapper();
    mapper.writer().writeValueAsString(user);
    }

    And this is the full exception:

    com.fasterxml.jackson.databind.JsonMappingException:
    No serializer found for class org.baeldung.jackson.exception.UserWithPrivateFields
    and no properties discovered to create BeanSerializer
    (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
    at c.f.j.d.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)

    5.2. The Solution

    We can solve this problem by configuring the ObjectMapper visibility:

    @Test
    public void givenClassWithPrivateFields_whenConfigureSerializing_thenCorrect()
    throws IOException {

    UserWithPrivateFields user = new UserWithPrivateFields(1, “John”);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    String result = mapper.writer().writeValueAsString(user);
    assertThat(result, containsString(“John”));
    }

    Or we can use the annotation @JsonAutoDetect:

    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    public class UserWithPrivateFields { … }

    Of course, if we do have the option to modify the source of the class, we can also add in getters for Jackson to use.

    6. JsonMappingException: Can Not Deserialize Instance Of

    6.1. The Problem

    Next, let’s take a look at JsonMappingException: Can Not Deserialize Instance Of.

    This exception is thrown if the wrong type is used while deserializing.

    In this example, we are trying to deserialize a List of User:

    @Test(expected = JsonMappingException.class)
    public void givenJsonOfArray_whenDeserializing_thenException()
    throws JsonProcessingException, IOException {

    String json
    = “[{“id”:1,”name”:”John”},{“id”:2,”name”:”Adam”}]”;
    ObjectMapper mapper = new ObjectMapper();
    mapper.reader().forType(User.class).readValue(json);
    }

    And here’s the full exception:

    com.fasterxml.jackson.databind.JsonMappingException:
    Can not deserialize instance of
    org.baeldung.jackson.dtos.User out of START_ARRAY token
    at [Source: [{“id”:1,”name”:”John”},{“id”:2,”name”:”Adam”}]; line: 1, column: 1] at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)

    6.2. The Solution

    We can solve this problem by changing the type from User to List:@Test
    public void givenJsonOfArray_whenDeserializing_thenCorrect()
    throws JsonProcessingException, IOException {

    String json
    = “[{“id”:1,”name”:”John”},{“id”:2,”name”:”Adam”}]”;

    ObjectMapper mapper = new ObjectMapper();
    List users = mapper.reader()
    .forType(new TypeReference<>>() {})
    .readValue(json);

    assertEquals(2, users.size());
    }

    7. UnrecognizedPropertyException

    7.1. The Problem

    Now let’s see the UnrecognizedPropertyException.

    This exception is thrown if there is an unknown property in the JSON String while deserializing.

    We’ll try to deserialize a JSON String with extra property “checked“:

    @Test(expected = UnrecognizedPropertyException.class)
    public void givenJsonStringWithExtra_whenDeserializing_thenException()
    throws IOException {

    String json = “{“id”:1,”name”:”John”, “checked”:true}”;

    ObjectMapper mapper = new ObjectMapper();
    mapper.reader().forType(User.class).readValue(json);
    }

    This is the full exception:

    com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
    Unrecognized field “checked” (class org.baeldung.jackson.dtos.User),
    not marked as ignorable (2 known properties: “id”, “name”])
    at [Source: {“id”:1,”name”:”John”, “checked”:true}; line: 1, column: 38] (through reference chain: org.baeldung.jackson.dtos.User[“checked”])
    at c.f.j.d.exc.UnrecognizedPropertyException.from(
    UnrecognizedPropertyException.java:51)

    7.2. The Solution

    We can solve this problem by configuring the ObjectMapper:

    @Test
    public void givenJsonStringWithExtra_whenConfigureDeserializing_thenCorrect()
    throws IOException {

    String json = “{“id”:1,”name”:”John”, “checked”:true}”;

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    User user = mapper.reader().forType(User.class).readValue(json);
    assertEquals(“John”, user.name);
    }

    Or we can use the annotation @JsonIgnoreProperties:

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class User {…}

    8. JsonParseException: Unexpected Character (”’ (code 39))

    8.1. The Problem

    Next, let’s discuss JsonParseException: Unexpected character (”’ (code 39)).

    This exception is thrown if the JSON String to be deserialized contains single quotes instead of double quotes.

    We’ll try to deserialize a JSON String containing single quotes:

    @Test(expected = JsonParseException.class)
    public void givenStringWithSingleQuotes_whenDeserializing_thenException()
    throws JsonProcessingException, IOException {

    String json = “{‘id’:1,’name’:’John’}”;
    ObjectMapper mapper = new ObjectMapper();

    mapper.reader()
    .forType(User.class).readValue(json);
    }

    Here’s the full exception:

    com.fasterxml.jackson.core.JsonParseException:
    Unexpected character (”’ (code 39)):
    was expecting double-quote to start field name
    at [Source: {‘id’:1,’name’:’John’}; line: 1, column: 3] at c.f.j.core.JsonParser._constructError(JsonParser.java:1419)

    8.2. The Solution

    We can solve this by configuring the ObjectMapper to allow single quotes:

    @Test
    public void
    givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect()
    throws JsonProcessingException, IOException {

    String json = “{‘id’:1,’name’:’John’}”;

    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
    ObjectMapper mapper = new ObjectMapper(factory);

    User user = mapper.reader().forType(User.class)
    .readValue(json);

    assertEquals(“John”, user.name);
    }

    Как выбрать определенное значение в APIJSON данных?

    • 1 подписчик
    • 2 часа назад
    • 25 просмотров

    ответа
    2

  • android
    • Android

    • +1 ещё

    Средний

  • Библиотека для работы с изображениями?

    • 2 подписчика
    • вчера
    • 70 просмотров

    ответ
    1

  • java
    • Java

    • +1 ещё

    Простой

  • Как добавить вместо Google maps API 2gis?

    • 1 подписчик
    • 19 окт.
    • 69 просмотров

    ответа
    2

  • Показать ещёЗагружается…
  • Вакансии с Хабр Карьеры

    Team/Tech lead java

    Сбер
    •Санкт-Петербург
    До 350 000 ₽

    Главный инженер по Java разработке

    Сбер
    •Вологда
    от 130 000 ₽

    Java разработчик (СберТранспорт)

    Сбер
    •Москва
    от 220 000 ₽
    Ещё вакансии

    Заказы с Хабр Фриланса

    Нужно осуществить администрирование лок. сети и оборудования(удаленно)

    21 окт. 2022, в 12:33
    8000 руб./за проект

    Создать страницу «Работа администратора с предложениями экспертов»

    21 окт. 2022, в 11:59
    1000 руб./за проект

    Реализовать бэк на Laravel

    21 окт. 2022, в 11:53
    100000 руб./за проект
    Ещё заказы

    Минуточку внимания

    Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями

    Зарегистрироваться

    Самое интересное за 24 часа

    • Почему из-за плагина w3tc не открывается страница?

      • 2 подписчика
      • 0 ответов
    • Smartctl ругается на нечитаемые сектора, но MegaCli делает вид, что всё в порядке, кому верить?

      • 2 подписчика
      • 0 ответов
    • Какая погрешность в количестве фиксаций целевых событий в Яндекс метрике допустима?

      • 2 подписчика
      • 0 ответов
    • Почему в Chrome не отображается круг, а получается квадрат?

      • 2 подписчика
      • 1 ответ
    • Как умножить матрицы с помощью SSE?

      • 3 подписчика
      • 0 ответов
    • Как сделать аутентификацию по номеру телефона?

      • 4 подписчика
      • 0 ответов
    • Как подождать асинхронного выполнения всех подписчиков события?

      • 3 подписчика
      • 0 ответов
    • Ломается весь код в Sublime Text?

      • 3 подписчика
      • 1 ответ
    • Периодически падает сайт с ошибкой 502 как найти проблему?

      • 3 подписчика
      • 2 ответа
    • Какой компилятор выбрать для C++?

      • 2 подписчика
      • 3 ответа
    • © Habr
    • О сервисе
    • Обратная связь
    • Блог

    Не запускается jar, хотя в Exclipse все работает, почему?

    • 1 подписчик
    • вчера
    • 33 просмотра

    ответов
    0

  • java
    • Java

    • +4 ещё

    Простой

  • 9. Jackson NoSuchMethodError

    Finally, let’s quickly discuss the Jackson “No such method” errors.

    When java.lang.NoSuchMethodError Exception is thrown, it’s usually because we have multiple (and incompatible) versions of Jackson jars on our classpath.

    This is the full exception:

    java.lang.NoSuchMethodError:
    com.fasterxml.jackson.core.JsonParser.getValueAsString()Ljava/lang/String;
    at c.f.j.d.deser.std.StringDeserializer.deserialize(StringDeserializer.java:24)

    10. Conclusion

    In this article, we did a deep dive into the most common Jackson problems — exceptions and errors — looking at the potential causes and at the solutions for each one.

    The implementation of all these examples and code snippets can be found on GitHub . This is a Maven-based project, so it should be easy to import and run as it is.

    Jackson bottom

    Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

    >> CHECK OUT THE COURSE Jackson footer banner

    Courses

    • All Courses
    • All Bulk Courses
    • All Bulk Team Courses
    • The Courses Platform
    Источники

    • https://www.baeldung.com/jackson-exception
    • https://qna.habr.com/q/1071104
    • https://www.codeproject.com/Questions/5301528/How-I-post-a-request-to-springboot-with-json-array
    [свернуть]
    Решите Вашу проблему!


    ×
    Adblock
    detector