[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>一、前言
我们在开发中难免和JSON打交道,这不小编最近遇到了。需要把一些信息转成JSON字符串,然后保存到数据库中。想到两种方式,一是新建实体类,然后转化为JSON,小编比较懒,直接Map多香呀!我们直接只有阿里巴巴的fastjson来进行转化即可,很方便!
<>二、理想转化展示
{"gender":"男","name":"小明","age":"18"} // 为空显示 {}
<>三、导入maven依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <
version>1.2.69</version> </dependency>
<>四、Map转化JSON字符串
private static String mapToJson() { Map<String,String> map = new HashMap<>();
map.put("age","18"); map.put("name","小明"); map.put("gender","男"); String string
= JSON.toJSONString(map); System.out.println(string); map.clear(); String
stringNull= JSON.toJSONString(map); System.out.println(stringNull); return
string; }
<>五、对象转JSON字符串
1. Pojo类
import lombok.Data; @Data public class UserPojo { private String name; private
String gender; private String age; }
2. 方法
private static String pojoToJson() { UserPojo userPojo = new UserPojo();
String stringNull= JSON.toJSONString(userPojo); System.out.println(stringNull);
userPojo.setAge("19"); userPojo.setGender("女"); userPojo.setName("小红"); String
string= JSON.toJSONString(userPojo); System.out.println(string); return string;
}
<>六、总结
这样就实现了哦,总体来说fastjson还是挺好用的,不过都说fastjson不安全,没有jackson安全。但是小编还是觉得fastjson用的比较多,也习惯了里面的方法了哈!!对你有帮助,点个赞呗!!