我把这个序列化的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\"}"
我需要将其反序列化为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
}
然后,我使用com.fasterxml.jackson.databind.ObjectMapper创建了捕获String并将其反序列化的方法
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();
}
}
}
然后在主类中调用该方法。
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);
}
}
运行它(使用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)
,而不必担心转义符。不确定这是否正确...