Spring无法使用空键返回JSON响应 [英] Spring fails to return JSON response with null key

查看:208
本文介绍了Spring无法使用空键返回JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我编写的代码.

@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 我收到以下回复

When I hit the URL localhost:8080/myapp/getData I receive the following response

10.5.1 500内部服务器错误 服务器遇到意外情况,阻止其满足请求.

10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request.

Even Spring也不会打印任何服务器端异常!

Even Spring does not print any server side exception as well!

我想知道为什么Spring无法处理键为null的JSON响应的根本原因.

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-映射空值或空键

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"));
}

这篇关于Spring无法使用空键返回JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆