Case insensitive deserialization
Growing up in Windows with BASIC you learn case doesn't matter, so Color
is the same as COLOR
or cOLOR
when it comes to variable names. Same applies to @Formula
or item names in Notes documents.
On the other side, Linux, Java, JavaScript and JSON are very much case sensitive.
This poses a challenge when deserializing (handcrafted) JSON files.
The Task at hand
Deserialization of JSON into a Java class instance can be done using jackson. This is also what the JsonObject in vert.x uses when you call json.mapTo(SomeClass)
. Not using vert.x? You can use the ObjectMapper
. Let's look at a sample Java class
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.vertx.core.json.JsonObject;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class JsonTest {
public static fromJson(final JsonObject source) {
return source.mapTo(JsonTest.class);
}
private String color;
private String shape;
private int answer;
private boolean pretty;
/* GETTERS and SETTERS omitted for brevity
Let your IDE add them for you */
}
Now you want to deserialize a good JSON, which works as expected:
{
"color": "Red",
"shape": "round",
"answer": 11,
"pretty": true
}
but the very moment your JSON isn't following proper capitalization, like human provided JSON,
{
"Color": "Red",
"Shape": "square",
"Answer": 42,
"pretty": true,
"ignore": "this"
}
deserialization will fail. We need to fix that.
Read more
Posted by Stephan H Wissel on 08 June 2022 | Comments (1) | categories: Java vert.x