missmatchdinputexception反序列化java字符串中的json字符串

gopyfrb3  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(458)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

六天前关门了。
改进这个问题
我正在尝试反序列化字符串中的json字符串。我从另一个系统得到这个响应并处理来自Kafka的响应,所以没有选择更改发布代码。额外的引号是个问题,但由于它是来自不同系统的消息,我的输入是固定的

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class TestModel {
    private Model model;
}

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Model {
    private String message;
}

驱动程序代码:

String t = "\"{\\\"model\\\":{\\\"message\\\":\\\"sample\\\"}}\"";
System.out.println(objectMapper.readValue(t, TestModel.class))  //Exception

当同一个字符串我试图反序列化如上我得到以下异常。

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `test.TestModel` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"model":{"message":"sample"}}')
 at [Source: (String)""{\"model\":{\"message\":\"sample\"}}""; line: 1, column: 1]
    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.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1373)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at Sample.main(Sample.java:15)

有人能告诉我这个。。

bksxznpy

bksxznpy1#

像这样的东西会有用的。

String t = "\"{\\\"message\\\":\\\"test\\\"}\"";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
JsonFactory factory = mapper.getFactory();
JsonParser createParser = factory.createParser(t);
JsonNode actualObj1 = mapper.readTree(createParser);
TestModel t11 = mapper.readValue(actualObj1.asText(), TestModel.class);
System.out.println(t11.getMessage());

下面是testmodel类

public class TestModel {

    public TestModel() {
    }

    @JsonProperty("message")
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

相关问题