JSON 无法构造 JSONConcatination 的实例:没有用于反序列化的字符串参数构造函数/工厂方法

Orb*_*rby 1 java json

我正在尝试使用以下 JSON 字符串创建一个带有另一个值映射的映射:

"{\"conditionField\":\"myFieldName\",\"conditionValue\":\"myFieldValue\",\"concatenationValues\":[\"fieldValue1\",\"fieldValue2\",\"fieldValue3\"]}"
Run Code Online (Sandbox Code Playgroud)

并在我尝试将其转换为 POJO 时获得以下 JsonMappingException:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of JSONConcatination: no String-argument constructor/factory method to deserialize from String value ('{"conditionField":"myFieldName","conditionValue":"myFieldValue","concatenationValues":["fieldValue1","fieldValue2","fieldValue3"]}')
 at [Source: "{\"conditionField\":\"myFieldName\",\"conditionValue\":\"myFieldValue\",\"concatenationValues\":[\"fieldValue1\",\"fieldValue2\",\"fieldValue3\"]}"; line: 1, column: 1]
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

private final Map<String, Map<String, List<String>>> jsonResources = new HashMap<String, Map<String, List<String>>>(); 



ObjectMapper mapper = new ObjectMapper();           
JSONConcatination jsonConcatination = mapper.readValue(json, JSONConcatination.class);
Map<String, List<String>> values = new HashMap<String, List<String>>();
values.put(jsonConcatination.getConditionValue(), jsonConcatination.getConcatenationValues());
jsonResources.put(jsonConcatination.getConditionField(), values);


@Data
public class JSONConcatination {

    private String conditionField;

    private String conditionValue;

    private List<String> concatenationValues;

}
Run Code Online (Sandbox Code Playgroud)

Sac*_*141 5

您的 JSON 字符串无效,首先使用以下替换操作使其成为有效字符串,这将删除 json 字符串中的开始和结束引号以及反斜杠。现在 jackson 会将其视为有效的 json 字符串。

json = json.replaceAll("^\"|\"$|\\\\", "");
Run Code Online (Sandbox Code Playgroud)

那么这将起作用。