Suppress wrapper object when serializing Java object into JSON using Jackson

后端 未结 5 2310
忘掉有多难
忘掉有多难 2021-02-14 23:45

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:35

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

提交回复
热议问题