美文网首页
springboot返回json和xml

springboot返回json和xml

作者: 莫夏_b560 | 来源:发表于2019-12-24 22:05 被阅读0次

    依赖!!!

    <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    

    1、在pojo层添加User类

    //被@XMLRootElement注解的类User,被描述为一个顶层的XML element */ 
    
    @XmlRootElement
     public class User {
    
        String userName;
        String userAge;
        String userAddress; public User(String userName, String userAge, String userAddress) { this.userName = userName; this.userAge = userAge; this.userAddress = userAddress;
        } 
    /** * 该注解可以将被注解的(非静态)字段,或者被注解的get/set方法对应的字段映射为本地元素,也就是子元素。
         */ 
    @XmlElement 
    public String getUserName() { return userName;
        } 
    public void setUserName(String userName) { this.userName = userName;
        }
    
        @XmlElement 
    public String getUserAge() { return userAge;
        } 
    
    public void setUserAge(String userAge) { this.userAge = userAge;
        }
    
        @XmlElement
     public String getUserAddress() { return userAddress;
        } 
    public void setUserAddress(String userAddress) { this.userAddress = userAddress;
        }
    }
    
    

    2、controller层

    @RestController
    public class UserController {
    
        //http://localhost:8080/json
        @GetMapping(value = "/json",produces = MediaType.APPLICATION_JSON_VALUE)
        public User index(){
            User user = new User("echola", "22", "深圳");
            return user;
        }
    
    
        //http://localhost:8080/xml
        @GetMapping(value = "/xml",produces = MediaType.APPLICATION_XML_VALUE)
        public User XML(){
            User user = new User("echola", "22", "深圳");
            return user;
        }
    }
    

    启动项目成功后,输入http://localhost:8080/json,页面上的json字符串:

    image

    输入http://localhost:8080/xml,页面上Xml格式:

    image

    相关文章

      网友评论

          本文标题:springboot返回json和xml

          本文链接:https://www.haomeiwen.com/subject/jxqqoctx.html