无法使用jackson

时间:2015-12-22 22:10:23

标签: java json serialization jackson

我正在编写客户端/服务器应用程序。我使用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}"

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你用作第一和第二的类型是什么?您使用的是哪个版本的杰克逊?我用Map<String, String>尝试了确切的代码,它运行正常。我正在运行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}