Suppress wrapper object when serializing Java object into JSON using Jackson

后端 未结 5 2139
时光取名叫无心
时光取名叫无心 2021-02-15 00:02

I have a web service that returns a list as JSON. It uses Jackson to map a List of Java POJOs into JSON. The problem is that the JSON representation has a wrapper object around

5条回答
  •  长情又很酷
    2021-02-15 00:29

    In a test mode when I run:

    org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
    String json = mapper.writeValueAsString( Arrays.asList("one","two","three","four","five") );
    System.out.println(json);
    

    returns:

    ["one","two","three","four","five"]
    

    which is the behavior you are expecting right?

    I could see that when I return this list via a Spring controller and let MappingJacksonJsonView handle transforming the list to a json, then yes there is a wrapper around it, which tells me that the MappingJacksonJsonView is the one adding the wrapper. One solution then would be to explicitly return the json from your controller, say:

        @RequestMapping(value = "/listnowrapper")
    public @ResponseBody String listNoWrapper() throws Exception{       
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(Arrays.asList("one","two","three","four","five")); 
    }
    

提交回复
热议问题