【发布时间】:2015-12-22 22:10:23
【问题描述】:
我正在编写一个客户端/服务器应用程序。我使用 jackson 在服务器上序列化我的 Objest 并将其发送到我的客户端,当我尝试将其反序列化回 HashMap 时,它会抛出此错误:
Can not instantiate value of type [map type; class java.util.HashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] from JSON String; no single-String constructor/factory method
认为我有 HashMap:
这是我如何在服务器上对其进行序列化:
@JsonUnwrapped
public static String convertObjectToJson(Object object) throws IOException {
ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = objectWriter.writeValueAsString(object);
return json;
}
这是我如何在客户端反序列化它:
@JsonCreator
public static <T, E> HashMap<T, E> deserializeToHashMap(String json, Class<T> firstType, Class<E> secondType) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
try {
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, firstType, secondType);
HashMap<T, E> map = mapper.readValue(json, mapType); //here is where i get the error
return map;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
这是我在客户端收到的一个简单的 json 字符串(它只包含一个值和一个键):
"{\r\n \"test\" : \"mohammad\"\r\n}"
我做错了什么?
【问题讨论】:
-
这是一个 JSON 字符串。它对应的 Java 类型是
String,而不是HashMap。如果您想将String解析为HashMap,您可以这样做。 -
如果你告诉我应该怎么做,我会很感激
标签: java json serialization jackson