Accepting / returning XML/JSON request and response - Spring MVC

前端 未结 5 796
無奈伤痛
無奈伤痛 2021-01-31 04:54

I need to write a rest service which accepts XML/JSON as a input (POST method) and XML/JSON as a output (based on the input format). I have tried a below approach to achieve thi

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 05:39

    i was facing the same problem like yours. Below is my solution and sample.

    Below is maven dependency that you need to include:

            
                com.fasterxml.jackson.core
                jackson-core
                2.4.3
            
            
                com.fasterxml.jackson.core
                jackson-databind
                2.4.3
            
            
                com.fasterxml.jackson.core
                jackson-annotations
                2.4.3
            
            
                com.fasterxml.jackson.dataformat
                jackson-dataformat-xml
                2.4.3
            
    

    dispatcher-servlet.xml

    
    
    
            
            
            
            
        
    

    and my @RequestMapping ( you can use your own request mapping )

    @RequestMapping(value = "/testXMLJSON",
                method = RequestMethod.GET, produces = {
                        MediaType.APPLICATION_XML_VALUE,
                        MediaType.APPLICATION_JSON_VALUE })
        @ResponseBody
        public ArtworkContentMessageType testXMLJSON()
        {
            //this is GS1 xml standard mapping.
            ArtworkContentMessageType resp = new ArtworkContentMessageType();
            StandardBusinessDocumentHeader standarBusinessDocumentHeader = new StandardBusinessDocumentHeader();
            resp.setStandardBusinessDocumentHeader(standarBusinessDocumentHeader );
            ArtworkContentType artWorkContent = new ArtworkContentType();
            resp.getArtworkContent().add(artWorkContent);
    
            return resp ;
        }
    

    If application/xml is required then, below headers must be present

    Content-Type:application/xml
    Accept:application/xml
    

提交回复
热议问题