我正在尝试使用Retrofit和Jackson来反序列化一个API。我得到的onFailure错误没有创造者,像默认构造,存在):不能从对象值反序列化(没有委托或基于属性的创造者。


当前回答

我得到了同样的错误,问题是我的模型没有实现Serializable,所以检查这个以及,可能会有所帮助,因为这也是原因之一。

其他回答

对于我们没有默认构造的类,例如当使用不可变对象时,Jackson默认情况下将不能将JSON反序列化为对象。 我们可以使用一些注释来解决这个问题,比如@JsonCreator,它可以帮助Jackson知道如何反序列化给定的JSON。

示例代码如下所示:

package com.test.hello;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Payment {

    private final Card card;

    private final Amount amount;

    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public Payment(@JsonProperty("card") Card card, @JsonProperty("amount") Amount amount) {
       this.card = card;
       this.amount = amount;
    }

    public Card getCard() {
       return card;
    }

    public Amount getAmount() {
        return amount;
    }
}

我得到了同样的错误,问题是我的模型没有实现Serializable,所以检查这个以及,可能会有所帮助,因为这也是原因之一。

我使用rescu与Kotlin,并通过使用@ConstructorProperties解决它

    data class MyResponse @ConstructorProperties("message", "count") constructor(
        val message: String,
        val count: Int
    )

Jackson使用@ConstructorProperties。这应该修复Lombok @Data以及。

我用Quarkus, Jackson和Lombok。所以我通过在模型类上添加@Jacksonized属性解决了这个问题。 所以所有的属性是:

@Jacksonized //missing
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ...

在类中添加构造函数 或 如果您正在使用pojo添加 @NoArgsConstructor @AllArgsConstructor

还要包括JsonProperty - @JsonProperty("name") private List<员工>姓名;