springmv返回JSON数据格式

1.先导入依赖

<!-- springmvc使用@responseBody  start-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>
<!-- springmvc使用@responseBody  end-->

2.Controller代码

//返回数据的json格式:  [{ id:2, pId:0, name:"系统管理", checked:true, open:true}]
@RequestMapping("/genzTreeNodes")
@ResponseBody
public List<HashMap<String, Object>> genzTreeNodes(Role role){
    
    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
    
    //遍历模块列表
    List<Module> moduleList = moduleService.find()//获取所有模块列表
    
    for (Module module : moduleList) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id", module.getId());
        //添加字符串
        map.put("pId", module.getParentId());                
        map.put("name", module.getName());
        //添加布尔类型
        map.put("checked", true);
        
        data.add(map);
    }
    //返回数据
    return data;
}

 

转载于:https://www.cnblogs.com/guo-rong/p/9533560.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要让 Java 接口返回 JSON 数据格式,你可以使用任何一个 JSON 库,比如 Jackson、Gson 或者 Fastjson。以下是使用 Jackson 库的示例代码: 首先,确保你的项目中已经引入了 Jackson 库的依赖。如果使用 Maven 管理项目依赖,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency> ``` 然后,在你的 Controller 中,可以按照如下方式编写代码: ```java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private ObjectMapper objectMapper; @GetMapping("/my-api") public MyResponse myApi() { MyResponse response = new MyResponse(); response.setCode(200); response.setMessage("Success"); // 设置其它字段... return response; } public static class MyResponse { private int code; private String message; // 其它字段... // 省略 getter 和 setter 方法... public String toJson() { try { return objectMapper.writeValueAsString(this); } catch (Exception e) { throw new RuntimeException(e); } } } } ``` 以上代码中,我们使用 Jackson 库的 ObjectMapper 对象将 Java 对象转换为 JSON 字符串。在 MyResponse 类中,我们添加了 toJson() 方法,该方法将 MyResponse 对象转换为 JSON 字符串。 当客户端请求 /my-api 接口时,MyController 的 myApi() 方法返回 MyResponse 对象,并且 MyResponse 对象会被自动转换为 JSON 格式数据返回给客户端。如果你想手动序列化对象为 JSON 字符串,可以调用 MyResponse.toJson() 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值