栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot返回json和xml的示例代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot返回json和xml的示例代码

有些情况接口需要返回的是xml数据,在springboot中并不需要每次都转换一下数据格式,只需做一些微调整即可。

新建一个springboot项目,加入依赖jackson-dataformat-xml,pom文件代码如下:



  4.0.0

  com.dalaoyang
  springboot_xml
  0.0.1-SNAPSHOT
  jar

  springboot_xml
  springboot_xml

  
    org.springframework.boot
    spring-boot-starter-parent
    1.5.9.RELEASE
     
  

  
    UTF-8
    UTF-8
    1.8
  

  
    
      org.springframework.boot
      spring-boot-starter-web
    

    
      org.springframework.boot
      spring-boot-devtools
      runtime
    
    
      org.springframework.boot
      spring-boot-starter-test
      test
    

    
      com.fasterxml.jackson.dataformat
      jackson-dataformat-xml
    
  

  
    
      
 org.springframework.boot
 spring-boot-maven-plugin
      
    
  

启动类默认即可,没有做任何调整。

新建一个user类,代码如下:

package com.dalaoyang.entity;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@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;
  }

  @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;
  }
}

最后是controller,代码如下:

package com.dalaoyang.controller;
import com.dalaoyang.entity.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

  //http://localhost:8080/json
  @GetMapping(value = "/json",produces = MediaType.APPLICATION_JSON_VALUE)
  public User index(){
    User user = new User("dalaoyang", "26", "北京");
    return user;
  }

  //http://localhost:8080/xml
  @GetMapping(value = "/xml",produces = MediaType.APPLICATION_XML_VALUE)
  public User XML(){
    User user = new User("dalaoyang", "26", "北京");
    return user;
  }
}

到这里就可以启动项目了,访问http://localhost:8080/json,可以看到如下图


访问http://localhost:8080/xml,如下图


源码下载 :https://gitee.com/dalaoyang/springboot_learn

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141141.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号