I'm new to Spring-boot and am trying to deserialize json array into java String using Jackson in a Spring-boot Application. Something like
{"history": ["historyA", "historyB"]} (JSON Request Body) -> String history;
However, the following error message got logged.
Cannot deserialize instance of `java.lang.String` out of START_ARRAY token
My Controller is similar to
@RestController
public class PatientController {
@PostMapping
public void create(@RequestBody @Valid Patient patient) {
mapper.create(patient);
}
}
My POJO is similar to:
@Data
@NoArgsConstructor
public class Patient {
@JsonDeserialize(contentUsing = PatientHistoryDeserializer.class, contentAs = List.class)
private String history;
My Json Deserializer is similar to:
public class PatientHistoryDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
List<String> histories = new LinkedList<>();
if (p.getCurrentToken() == JsonToken.START_ARRAY) {
while (p.getCurrentToken() != JsonToken.END_ARRAY) {
String history = p.getValueAsString();
if(history.contains("#"))
throw new ClientError(HttpServletResponse.SC_BAD_REQUEST, "invalid...");
histories.add(history);
}
}
return String.join("#", histories);
}
}
Is my goal achievable ? Or any suggestions on how to convert as I wanted ?