无法反序列化json:MismatchedInputException。与静态类一起使用

时间:2019-11-18 12:36:22

标签: java jackson deserialization inner-classes

我正在使用帮助内部类反序列化一些输入。当我使用静态类时,反序列化工作。

    public class Test {

    public static void main(String[] args) throws IOException {
        String message = "{\"location\":\"https://some.com\"}";
        URL url = new ObjectMapper()
                .readValue(message, Loc.class).getLocation();
        System.out.println(url.toString());
    }

        @Getter
        @Setter
        private class Loc {
            URL location;
        }

}

在上面运行主类时出现错误:

    Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `Test$H$Loc` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: (String)"{"location":"https://some.com"}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1294)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)

当我将类设为静态时,一切正常。但是我需要非静态类。怎么了?

UPD:我可以通过使Loc类成为外部类而不是内部类来解决此问题。我的问题是,当我想将Loc作为内部类使用时,为什么要将其静态化以进行序列化? UPD:删除了无关紧要的内部类H

2 个答案:

答案 0 :(得分:0)

为什么需要如此奇怪的结构?但是无所谓。如果需要这样的结构,则需要将Hstatic以及Loc做为

公共课程测试{

public static void main(String[] args) throws IOException {
    String message = "{\"location\":\"https://some.com\"}";
    URL url = new ObjectMapper()
            .readValue(message, H.Loc.class).getLocation();
    System.out.println(url.toString());
}

private static class H {
    @Getter
    @Setter
    @NoArgsConstructor
    private static class Loc {
        URL location;
    }
}

}

答案 1 :(得分:-1)

尝试类似的方法

public class Outer {
    static class Inner {
      // your stuff
    }
}   

如果不添加静态对象,则生成的类通常对于Jackson以及任何其他数据绑定框架(Hibernate,JAXB)都没有用;通常可以序列化,但不能序列化到。