I want to convert json via jackson library to a map containing camelCase key...say...
from
{
\"SomeKey\": \"SomeValue\",
\"Anoth
The following will transform json with keys on any "case format" to using camelCased keys:
/**
* Convert all property keys of the specified JSON to camelCase
*/
public static String toJsonWithCamelCasedKeys(String json) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new SimpleModule()
.addKeySerializer(String.class, new JsonSerializer<>() {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String key = CaseUtil.toCamelCase(value);
gen.writeFieldName(key);
}
})
);
try {
Map jsonMap = objectMapper.readValue(json, new TypeReference<>() {});
return objectMapper.writeValueAsString(jsonMap);
} catch (Exception e) {
throw new JsonException("Error transforming JSON", e);
}
}
...and a CaseUtil implementation could be something like this:
import java.util.Arrays;
import java.util.stream.Collectors;
public class CaseUtil {
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
else if (s.isBlank()) {
return "";
}
return decapitaliseFirstLetter(
String.join("", Arrays.stream(s.split("[-_\\s]"))
.map(CaseUtil::capitaliseFirstLetter)
.collect(Collectors.toList()))
);
}
private static String capitaliseFirstLetter(String s) {
return (s.length() > 0)
? s.substring(0, 1).toUpperCase() + s.substring(1)
: s;
}
private static String decapitaliseFirstLetter(String s) {
return (s.length() > 0)
? s.substring(0, 1).toLowerCase() + s.substring(1)
: s;
}
}
A unit test:
@Test
void jsonWithMiscCasedPropKeys_shouldConvertKeyToCamelCase() throws Exception {
String inputJson =
"{\"kebab-prop\": \"kebab\"," +
"\"snake_prop\": \"snake\"," +
"\"PascalProp\": \"pascal\"," +
"\"camelCasedProp\": \"camel\"}";
String expectedJson =
"{\"kebabProp\": \"kebab\"," +
"\"snakeProp\": \"snake\"," +
"\"pascalProp\": \"pascal\"," +
"\"camelCasedProp\": \"camel\"}";
String actualJson = Json.toJsonWithCamelCasedKeys(inputJson);
JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.LENIENT);
}