一,什么是FastJson? 1,Fastjson是Java语言编写的高性能的JSON处理器,由阿里巴巴公司开发。 2,不需要额外的jar,能够直接跑在JDK上。 3,FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库,看成速度最快。 4,FastJson直接java bean的直接序列化,易上手。
二,官方网址: 点击打开fastjson网址
三,将java bean序列化为JSON对象 1,编写java 实体类
public class Product {
private Integer id;
private String name;
private Integer price;
private Date birthday;
public Product(Integer id, String name, Integer price, Date birthday) {
this.id = id;
this.name = name;
this.price = price;
this.birthday = birthday;
}
public Product() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
2,在controller中实现序列化
@RestController
@RequestMapping("/fastjson")
public class FastjsonController {
private static Map<Integer, Product> productMap = new HashMap<>();
static {
productMap.put(1,new Product(1,"口红",399,new Date()));
productMap.put(2,new Product(2,"眼影",199,new Date()));
productMap.put(3,new Product(3,"眉笔",99,new Date()));
productMap.put(4,new Product(4,"唇釉",299,new Date()));
}
/** * 将java对象序列化为JSON * @param id * @return * @throws JsonProcessingException */
@GetMapping("/products/{id}")
public Product getProductById(@PathVariable("id") Integer id) throws JsonProcessingException {
Product product = productMap.get(id);
//将Java对象序列化为JSON对象
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
//String jsonString = JSON.toJSONString(product);
String jsonString = JSON.toJSONString(product, SerializerFeature.WriteDateUseDateFormat);
System.out.println("===FastJSON序列化的字符串:"+jsonString);
return product;
}
}
四,将JSON对象反序列为java对象
直接在上面的controller中添加一个方法即可。
/** * 把JSON字符串反序列化为java对象 * @return */
@GetMapping("/getUserByJson")
public Product getProductByJSON(){
//准备一个JSON字符串
String json = "{\"birthday\":1627467232616,\"id\":2,\"name\":\"眼影\",\"price\":199}";
Product product = JSON.parseObject(json, Product.class);
System.out.println("===FastJSON反序列化的java对象:"+product);
return product;
}
接下来开始测试
五,总结 fastjson虽然在序列化、反序列化上将速度提到了最快,但是,FastJson有时会在复杂类型的Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用,这方面有点缺欠,不如jackson做得好。 如果你需要使用jackson序列化JSON的话,可以查看博客——Jackson序列化和反序列化java对象
好了,小伙伴们,基本操作就完成了,如果大家有什么问题的话,可以再下方评论处留下宝贵的意见哦。
本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/qq_46540738/article/details/119189652