zoukankan      html  css  js  c++  java
  • 【java框架】SpringMVC(4) -- JSON相关的数据返回

    项目中我们经常会使用到JSON的数据格式,这里回顾了一下JSON相关的知识点。对日常使用到的JSON工具做一些简单的补充。

    1.JSON工具

    1.1.fastjson工具包

    在实际项目中我们经常会使用alibabba的fastjson来替代jackson的jar包,因为fastjson已经集成了jackson的功能,用于前台返回json string或者是JSON和Object Java对象

    的互相转换都有了非常灵活好用的API支持。

    maven依赖的引入:

    <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
          <version>1.2.60</version>
    </dependency>

    1.2.ObjectMapper类

    ObjectMapper类是jackson包中的一个用于将java实体类转为json的String字符串进行输出的实用类。

    这里主要使用了其中的writeValueAsString方法。

    @RestController
    @RequestMapping("/user")
    public class UserController {
        @RequestMapping("/json")
        public String jsonStr() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            User user = new User("枫夜Alex", 5, "男");
            String value = mapper.writeValueAsString(user);
            return value;
        }
    
        @RequestMapping("/date")
        public String dateJsonStr() throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            //不使用时间戳的方式
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //自定义日期格式对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //指定日期格式
            mapper.setDateFormat(sdf);
            Date date = new Date();
            String value = mapper.writeValueAsString(date);
            return value;
        }
    
        @RequestMapping("/dateutil")
        public String jsonUtil(){
            ObjectMapper mapper = new ObjectMapper();
            Date date = new Date();
            String value = JsonUtils.getJson(date);
            return value;
        }
    }

    封装了一个JsonUtils类进行Date格式化转换:

    public class JsonUtils {
        public static String getJson(Object object) {
            return getJson(object,"yyyy-MM-dd HH:mm:ss");
        }
    
        public static String getJson(Object object,String dateFormat) {
            ObjectMapper mapper = new ObjectMapper();
            //不使用时间差的方式
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //自定义日期格式对象
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            //指定日期格式
            mapper.setDateFormat(sdf);
            try {
                return mapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    最后测试一下前端输出:

     

    1.3.对象与JSON的互转

    这里主要是使用到fastjson的API,比较简单,直接上代码:

    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class JsonDemoApplicationTests {
        @Test
        public void contextLoads() {
            //创建一个对象
            User user1 = new User("枫夜1号", 3, "男");
            User user2 = new User("枫夜2号", 3, "男");
            User user3 = new User("枫夜3号", 3, "男");
            User user4 = new User("枫夜4号", 3, "男");
            List<User> list = new ArrayList<User>();
            list.add(user1);
            list.add(user2);
            list.add(user3);
            list.add(user4);
    
            System.out.println("*******Java对象 转 JSON字符串*******");
            String str1 = JSON.toJSONString(list);
            System.out.println("JSON.toJSONString(list)==>"+str1);
            String str2 = JSON.toJSONString(user1);
            System.out.println("JSON.toJSONString(user1)==>"+str2);
    
            System.out.println("
    ****** JSON字符串 转 Java对象*******");
            User jp_user1=JSON.parseObject(str2,User.class);
            System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
    
            System.out.println("
    ****** Java对象 转 JSON对象 ******");
            JSONObject object = (JSONObject)JSON.toJSON(user2);
            System.out.println("(JSONObject) JSON.toJSON(user2)==>"+object.getString("name"));
    
            System.out.println("
    ****** JSON对象 转 Java对象 ******");
            User user = JSON.toJavaObject(object, User.class);
            System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+user);
        }
    }

    博文参考:

    https://mp.weixin.qq.com/s/RAqRKZJqsJ78HRrJg71R1g

    https://www.runoob.com/json/json-tutorial.html

  • 相关阅读:
    fullCalendar改造计划之带农历节气节假日的万年历(转)
    Linked List Cycle
    Remove Nth Node From End of List
    Binary Tree Inorder Traversal
    Unique Binary Search Trees
    Binary Tree Level Order Traversal
    Binary Tree Level Order Traversal II
    Plus One
    Remove Duplicates from Sorted List
    Merge Two Sorted Lists
  • 原文地址:https://www.cnblogs.com/yif0118/p/15028358.html
Copyright © 2011-2022 走看看