Below is the code I have written.
@RequestMapping(value = "/getData", method = RequestMethod.GET)
public @ResponseBody Map<String,String> test() throws IOException {
Map<String,String> map = new HashMap<String,String>();
map.put("key","value");
map.put(null, "Key's Value"); //**This highlighted code causing the problem, if I remove this then it works fine.**
return map;
}
When I hit the URL localhost:8080/myapp/getData
I receive the following response
10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request.
Even Spring does not print any server side exception as well!
I want to know the root cause why Spring can't handle JSON response with key as null.
If you want a null key follow this
http://www.baeldung.com/jackson-map-null-values-or-null-key
class MyDtoNullKeySerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException {
jsonGenerator.writeFieldName("");
}
}
@Test
public void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer());
MyDto dtoObject = new MyDto();
dtoObject.setStringValue("dtoObjectString");
Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject);
String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("\"\""));
assertThat(dtoMapAsString, containsString("dtoObjectString"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With