利用fastjson工具实现JSON、对象、数组、map互转

利用fastjson工具实现JSON、对象、数组、map互转

一、工具介绍

关于Object转换Json,常用的框架并不多,主要是这几个:

  • Jackson: 这个框架基本成为了Spring的标配。
  • FastJson : 这个是国内的,出自阿里的开源json框架,效率会比较高。
  • Gson : 没怎么用过。

这里阐述使用FastJson工具

由于json格式经常容易写错,所以推荐个json校验工具:http://www.bejson.com/

FastJson入门教程参考W3Cschool: https://www.w3cschool.cn/fastjson/fastjson-ex1.html

fastjson.jar包原始下载地址:https://github.com/alibaba/fastjson

二、springboot进行集成FastJson。

导包

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

三、使用

1、对象<-->JSON

        //下面的student为对象
        // TODO 用户对象转JSON串
        String jsonString = JSON.toJSONString(student);
        System.out.println("jsonString:" + jsonString);
        // TODO JSON串转用户组对象
        UserGroup student2= JSON.parseObject(jsonString, Student.class);
        System.out.println("student2:" + student2);

2、数组->json字符串->list

        // 构建用户对象数组
        User[] users = new User[]{user1,user2};
        // 用户对象数组转JSON串
        String jsonString2 = JSON.toJSONString(users);
        System.out.println("jsonString2:" + jsonString2);
        // JSON串转用户对象列表
        List<User> users2 = JSON.parseArray(jsonString2, User.class);
        System.out.println("users2:" + users2);

 

3、List -> JSON array     JSON array -> List

                //List -> JSON array 
		List<Bar> barList = new ArrayList<Bar>(); 
		barList.add(new Bar()); 
		barList.add(new Bar()); 
		barList.add(new Bar()); 
		String json= JSON.toJSONString(barList, true); 
		System.out.println(json); 

		//JSON array -> List 
		List<Bar> barList1 = JSON.parseArray(json,Bar.class); 
		for (Bar bar : barList1) { 
			System.out.println(bar.toString()); 
		} 

4、Map -> JSON     JSON -> Map

                //Map -> JSON 
		Map<String,Bar> map = new HashMap<String, Bar>(); 
		map.put("a",new Bar()); 
		map.put("b",new Bar()); 
		map.put("c",new Bar()); 
		String json = JSON.toJSONString(map,true); 
		System.out.println(json); 

		//JSON -> Map 
		Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json); 
	

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值