zoukankan      html  css  js  c++  java
  • JSON返回数据的几种方式

    Java开发难免要使用JSON传递数据,下面是我总结的几种回调方式。

    推荐文章:JSON、JSONObject、JSONArray、Map之间的关系

    方式一、返回Map集合

    //返回Map集合
    @RequestMapping("/findStudent")
    @ResponseBody
    public Map<String, Object> findStudent(MultipartFile file) {
    
        Student student = new Student();
        student.setUsername("木心");
        student.setPassword("123456");
    
        Map map = new HashMap<String, Object>();
        map.put("code", 1);
        map.put("msg", "成功");
        map.put("student",student);
    
        return map;
    }

    方式二、返回JSON对象

    //返回JSONObject对象
    @RequestMapping(value = "/findStudent2")
    @ResponseBody
    public JSONObject findStudent2(String id){
    
        Student student = new Student();
        student.setUsername("木心");
        student.setPassword("123456");
    
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 1);
        jsonObject.put("msg", "成功");
        jsonObject.put("student",student);
    
        return jsonObject;
    }

    方式三、返回JSON数组

    //返回JSON数组
    @RequestMapping(value = "/findStudent3")
    @ResponseBody
    public JSONArray findStudent3(String id){
    
        Student student = new Student();
        student.setUsername("木心");
        student.setPassword("123456");
    
        Student student2 = new Student();
        student2.setUsername("小白菜");
        student2.setPassword("1234567");
    
        JSONArray json = new JSONArray();
        json.add(student);
        json.add(student2);
        return  json;
    }
  • 相关阅读:
    练习5-3 数字金字塔 (15分)
    JSTL标签
    ssm+mysql+jsp打造在线考试系统WeKnow-学生端
    JSP常用内置对象
    mybatis入门2
    mybtis入门
    数据源的作用
    ssm动态查询向前台传json
    ssm中的注解
    ssm中的模糊查询
  • 原文地址:https://www.cnblogs.com/mxxbc/p/14039005.html
Copyright © 2011-2022 走看看