【问题标题】:Can't Deserialize HashMap using jackson无法使用杰克逊反序列化 HashMap
【发布时间】: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


【解决方案1】:

你使用什么类型作为第一和第二?你用的是哪个版本的杰克逊?我用Map&lt;String, String&gt; 尝试了确切的代码,它工作正常。我正在运行 Java 8 和 Jackson 2.6.0

    String json = "{\r\n  \"test\" : \"mohammad\"\r\n}";
    try {
        HashMap<String, String> map = deserializeToHashMap(json, String.class, String.class); 
        System.out.println(map);
    } catch (Exception e) {
        e.printStackTrace();
    }

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); <- does not compile for me
    try {
        TypeFactory typeFactory = mapper.getTypeFactory();
        JavaType 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;
    }
}

得到输出

{test=mohammad}

【讨论】:

  • 仍然不适合我。我使用 jackson 1.9.9 和 java 8,第一个和第二个是 String.class 和 String.class
  • 你能把jackson升级到新版本吗?
  • 我做了但仍然没有工作。我也尝试过使用 Gson,但没有希望!
猜你喜欢
  • 2017-06-23
  • 2019-08-04
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多