gpt4 book ai didi

java - 无法从 START_OBJECT 标记 String.class 反序列化 java.lang.String 的实例

转载 作者:行者123 更新时间:2023-12-02 10:51:34 24 4
gpt4 key购买 nike

我第一次遇到将 ObjectMapper 与 String.class 一起使用。我尝试将 json 作为字符串给出,但得到了 JsonMappingException。您能帮忙解释一下原因吗?

public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{
String response="{\"response\":\"success\"}";
ObjectMapper objectMapper = new ObjectMapper();
Object object = objectMapper.readValue(response, String.class);
System.out.println(object);
}

回应:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: {"response":"success"}; line: 1, column: 1] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270) at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)

在一次试验中,当我将响应传递为“成功”时,我得到:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'success': was expecting ('true', 'false' or 'null')

最佳答案

正确的方法是read it as tree :

ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree("{\"response\":\"success\"}");
String response = tree.get("response").asText();
System.out.println(response);

输出:成功

关于java - 无法从 START_OBJECT 标记 String.class 反序列化 java.lang.String 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52147975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com