Creating a custom deserializer
Create a custom deserializer to get the raw JSON value. You can choose one of the following implementations, according to your needs:
- It will give you the JSON as is, that is, keeping all the spaces and tabs:
public class RawJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
long begin = jp.getCurrentLocation().getCharOffset();
jp.skipChildren();
long end = jp.getCurrentLocation().getCharOffset();
String json = jp.getCurrentLocation().getSourceRef().toString();
return json.substring((int) begin - 1, (int) end);
}
}
- It will give you the JSON without extra spaces and tabs:
public class RawJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
return mapper.writeValueAsString(node);
}
}
Annotate your class to use the deserializer defined above
Change the Entity class by annotating the children attribute with @JsonDeserialize referencing the deserializer defined above:
public class Entity {
public String id;
@JsonDeserialize(using = RawJsonDeserializer.class)
public String children;
}
Parsing the JSON
Then parse the JSON using ObjectMapper and Jackson will use your custom deserializer:
String json = "{\"id\":\"1\",\"children\":[\"2\",\"3\"]}";
ObjectMapper mapper = new ObjectMapper();
Entity entity = mapper.readValue(json, Entity.class);
The value of the children attribute will be ["2","3"].
For more details, have a look at this question.
childrentoList<String>?