使用 Jackson 将 JSON 反序列化为 Java 对象:没有从字符串值反序列化的字符串参数构造函数/工厂方法

key*_*ger 5 java json jackson jackson-databind

我有这个序列化的 JSON 作为字符串给我

"{\"UniqueId\":[\"69570d12-598d-4aca-abe9-4d0e7b286fe5\",\"949cd142-3eca-4fd8-b8ea-b681f65c69ca\"],\"CustomerOffers\":{\"137966\":[05],\"137986\":[11],\"137987\":[38]},\"Success\":true,\"ErrorMessages\":[\"No Error\"],\"ErrorType\":\"null\"}"
Run Code Online (Sandbox Code Playgroud)

我需要将它反序列化为 Java 对象。

我创建了这个对象类

public class Data {

    public List<UUID> UniqueId;
    public Map<Integer, List<Integer>> CustomerOffers;
    public Boolean Success;
    public List<String> ErrorMessages;
    public String ErrorType;    

   // Usual Getters and Setters here
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了获取字符串并反序列化它的方法,使用 com.fasterxml.jackson.databind.ObjectMapper

public class Deserializing {

public void processing(String input){

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        try {

            // JSON string to Java object
            Data data = mapper.readValue(input, Data.class); //This returns exception
            System.out.println(data);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    
}
Run Code Online (Sandbox Code Playgroud)

然后主类调用方法。

public class Testing {

    @Test
    private void testing() throws ClassNotFoundException {
    Deserializing deserializing = new Deserializing();
    String rawData =  "\"{\\\"UniqueId\\\":[\\\"69570d12-598d-4aca-abe9-4d0e7b286fe5\\\",\\\"949cd142-3eca-4fd8-b8ea-b681f65c69ca\\\"],\\\"CustomerOffers\\\":{\\\"137966\\\":[05],\\\"137986\\\":[11],\\\"137987\\\":[38]},\\\"Success\\\":true,\\\"ErrorMessages\\\":[\\\"No Error\\\"],\\\"ErrorType\\\":\\\"null\\\"}\"";
    deserializing.processing(rawData);
    }

}
Run Code Online (Sandbox Code Playgroud)

运行后(使用 TestNG),我收到此错误消息

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of数据(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value

我想知道,我哪里做错了?

谢谢你

PS:我从txt文件中得到的原始序列化JSON数据看起来像这样 "{\"UniqueId\":[\"69570d12-598d-4aca-abe9-4d0e7b286fe5\",\"949cd142-3eca-4fd8-b8ea-b681f65c69ca\"],\"CustomerOffers\":{\"137966\":[48],\"137986\":[48],\"137987\":[48]},\"Success\":true,\"ErrorMessages\":[\"No Error\"],\"ErrorType\":\"null\"}"
当我将其复制粘贴到IntelliJ编辑器时,需要添加转义字符串(IntelliJ自动添加)。如果我直接从 txt 文件中获取数据并使用它,我只需将它传递给方法,public void processing(String input)而不必担心转义字符。虽然不确定这是否正确......