jackson 无法将类型“java.lang.String”的值转换为所需的类型- java.lang.IllegalStateException:

chy5wohz  于 7个月前  发布在  Java
关注(0)|答案(1)|浏览(84)

我正在开发一个spring Boot 应用程序,并试图使用Jackson来实现json。
我得到下面的错误,当我尝试这样做。

Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'student.StudentId' for property 'student.ref.null'; Cannot convert value of type 'java.lang.String' to required type 'student.StudentId': no matching editors or conversion strategy found
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:594)
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:682)
... 104 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'student.StudentId': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:262)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:589)
    ... 105 common frames omitted

我不明白为什么会发生这种情况,因为StudentId类有一个将String转换为StudentId的方法。

@Data
@Getter(onMethod_ = {@JsonValue})
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)

public class StudentId {
    private final long value;
    @JsonCreator
    public static StudentId from(long value) {
        return new StudentId(value);
    }

    @JsonCreator
    public static StudentId from(String value) {
        long longValue = Long.parseLong(value);
        return StudentId.from(longValue);
    }

    @JsonCreator
    public static StudentId from(BigDecimal value) {
        long longValue = value.longValue();
        return StudentId.from(longValue);
    }

    public String stringValue() {
        return String.valueOf(value);
    }
}

下面是我正在尝试转换的json的相关部分。开始,这里的StudentId是一个长值,它应该由处理长值的方法处理。所以我不知道这哪里出错了。

"data":{
     "Student1":{
        "type":"undergrad",
        "studentId":501043
      }
}

有没有人能指出我做错了什么或如何解决这个问题?
先谢了。

hmae6n7t

hmae6n7t1#

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class StudentId {

    private final long value;

    @JsonCreator
    public static StudentId from(@JsonProperty("studentId") long value) {
        return new StudentId(value);
    }

    @JsonCreator
    public static StudentId from(@JsonProperty("studentId") String value) {
        return from(Long.parseLong(value));
    }

    @JsonCreator
    public static StudentId from(@JsonProperty("studentId") BigDecimal value) {
        return from(value.longValue());
    }

}

这个类成功解析了以下json:

{
   "type": "undergrad",
   "studentId": 501043
}

相关问题