How to filter the json response returning from spring rest web service

前端 未结 4 1352
后悔当初
后悔当初 2021-01-17 03:28

How to filter the json response returning from spring rest web service.

When use call the customEvents i only need to outout the eventId and the Event name only. Whe

4条回答
  •  灰色年华
    2021-01-17 04:14

    You can use @JsonFilter to archive.

    Pojo:

    @JsonFilter("myFilter")
    public class User {
        ....
    }
    

    Controller:

    public String getUser(
                @RequestParam(value="id") String id, 
                @RequestParam(value="requiredFields",required=false ) String requiredFields
            ) throws JsonParseException, JsonMappingException, IOException {
    
        //Get User 
        User user = userService.getUser(id);
        //Start
        ObjectMapper mapper = new ObjectMapper();
        // and then serialize using that filter provider:
        String json="";
        try {
            if (requiredFields!= null) {
                String[] fields = requiredFields.split("\\,");
    
                FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
                SimpleBeanPropertyFilter.filterOutAllExcept(new HashSet(Arrays
                      .asList(fields))));
    
                json = mapper.filteredWriter(filters).writeValueAsString(user);//Deprecated 
            } else {
                SimpleFilterProvider fp = new SimpleFilterProvider().setFailOnUnknownId(false);
                mapper.setFilters(fp);
                json =mapper.writeValueAsString(user);
            }
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return json;
    }
    

    Get URL: .....&requiredFields=id,Name,Age

提交回复
热议问题