Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring fails to return JSON response with null key

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.

like image 452
Zaid Avatar asked Mar 15 '23 12:03

Zaid


1 Answers

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"));
}
like image 141
dom farr Avatar answered Mar 23 '23 12:03

dom farr