标签:简单 reference htm java 反序列化 -- tmp st3 fas
把类的对象存储到字符串可存储
public interface JsonInterface { }
mport com.alibaba.fastjson.JSON; import lombok.Getter; import lombok.Setter; @Setter @Getter public class JsonVo implements JsonInterface { private String id; private String name; public JsonVo(String id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return String.format("id:%s |||| name:%s", id, name); } }
public void test() { JsonInterface tmp = new JsonVo("id1", "name1"); String json = JSON.toJSONString(tmp); System.out.println(json); JsonInterface jsonVo = JSON.parseObject(json, JsonVo.class); System.out.println(jsonVo); System.out.println("--------"); byte[] bytes = JSON.toJSONBytes(tmp); System.out.println(bytes); JsonInterface jsonVo2 = JSON.parseObject(bytes, JsonVo.class); System.out.println(jsonVo2); }
结果
{"id":"id1","name":"name1"} id:id1 |||| name:name1 -------- [B@383534aa id:id1 |||| name:name1
Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景
例1
public void test2() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(9); list.add(4); list.add(8); JSONObject jsonObj = new JSONObject(); jsonObj.put("a", list); System.out.println(jsonObj); List<String> list2 = jsonObj.getObject("a", new TypeReference<List<Integer>>(){}); System.out.println(list2); }
结果
{"a":[1,9,4,8]} [1, 9, 4, 8]
例2
public void test3() { List<JsonVo> list = new ArrayList<>(); list.add(new JsonVo("id1", "name1")); list.add(new JsonVo("id2", "name2")); list.add(new JsonVo("id3", "name3")); JSONObject jsonObj = new JSONObject(); jsonObj.put("a", list); System.out.println(jsonObj); List<String> list2 = jsonObj.getObject("a", new TypeReference<List<JsonVo>>(){}); System.out.println(list2); }
结果
{"a":[{"id":"id1","name":"name1"},{"id":"id2","name":"name2"},{"id":"id3","name":"name3"}]} [id:id1 |||| name:name1, id:id2 |||| name:name2, id:id3 |||| name:name3]
com.alibaba.fastjson.JSON对类对象的序列化与反序列化
标签:简单 reference htm java 反序列化 -- tmp st3 fas
原文地址:https://www.cnblogs.com/kaituorensheng/p/9886425.html