@Test
public void ObjectToJson(){
AreasEntity area = new AreasEntity();
AreasEntity area1 = new AreasEntity();
ArrayList<AreasEntity> list = new ArrayList<>();
area.setId(1L).setCode("ll").setName("工商局");
area1.setId(1L).setCode("ll").setName("工商局");
list.add(area);
list.add(area1);
String s = JSON.toJSONString(list);
System.out.println(s);
//[{"code":"ll","id":1,"name":"工商局"},{"code":"ll","id":1,"name":"工商局"}]
}
@Test
public void MapToJson(){
AreasEntity area = new AreasEntity();
AreasEntity area1 = new AreasEntity();
Map<String, Object> map = new HashMap<>();
area.setId(1L).setCode("ll").setName("工商局");
area1.setId(1L).setCode("ll").setName("工商局");
map.put("area1", area);
map.put("area2", area1);
String s = JSON.toJSONString(map);
System.out.println(s);
//{"area1":{"code":"ll","id":1,"name":"工商局"},"area2":{"code":"ll","id":1,"name":"工商局"}}
}
@Test
public void JsonToMap(){
// String s = "\"area1\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}";
//字符串转成对象
String s = "{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}";
AreasEntity areasEntity = JSON.parseObject(s, AreasEntity.class);
System.out.println(areasEntity);
//list集合转成对象。静态方法:parseArray
String s1 = "[{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"},{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}]";
List<AreasEntity> areasEntities = JSON.parseArray(s1, AreasEntity.class);
System.out.println(areasEntities);
//map转成对象 。静态方法:parseObject
//直接进行反序列化,Map集合是没有泛型的,泛型没有是不安全的集合
//参数是TypeReference类型
String s3 = "{\"area1\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"},\"area2\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}}";
Map<String, AreasEntity> areasEntityMap = JSON.parseObject(s3, new TypeReference<Map<String, AreasEntity>>() {});
for (String key : areasEntityMap.keySet()) {
System.out.println(key+" " +areasEntityMap.get(key));
}
}
FastJson
最新推荐文章于 2024-11-03 11:01:20 发布