下面是我写的代码。
@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;
}
当我点击 URL localhost:8080/myapp/getData
我收到以下回复
10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request.
即使是 Spring 也不会打印任何服务器端异常!
我想知道 Spring 无法处理 key 为 null 的 JSON 响应的根本原因。
最佳答案
如果你想要一个空键按照这个
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"));
}
关于java - Spring 无法使用空键返回 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33075147/