思维导图
1、转换为对象
package com.lj.demo; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonDemo1 { public static void main(String[] args) throws Exception { // 一:实体类转换成Json串-》json对象 JsonObject1 obj1 = new JsonObject1("l1", "学生管理", "closed"); ObjectMapper om = new ObjectMapper(); System.out.println(om.writeValueAsString(obj1)); // 二:map集合转成json串-》json对象 Map<String, Object> map = new HashMap<String, Object>(); map.put("id", "11"); map.put("text", "xues"); map.put("state", "closed"); System.out.println(om.writeValueAsString(map)); } }
运行结果
2、转换成数组
package com.lj.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonDemo2 { //方式一:获取json数组 实体类对象转换成json ——> json数组 public static void main(String[] args) throws Exception { JsonObject1 obj1=new JsonObject1("14", "about.html", "null"); JsonObject1 obj2=new JsonObject1("15", "welcome.html", "null"); List<JsonObject1> list=new ArrayList<>(); list.add(obj1); list.add(obj2); ObjectMapper om=new ObjectMapper(); System.out.println(om.writeValueAsString(list)); //方式二:map集合对象转换成json数组 Map<String, Object> map=new HashMap<String, Object>(); map.put("id","14"); map.put("text","about.html"); map.put("state", null); Map<String, Object> map2=new HashMap<String, Object>(); map2.put("id","15"); map2.put("text","welcome.html"); map2.put("state",null); List<Map<String, Object>> listMap=new ArrayList<>(); listMap.add(map); listMap.add(map2); System.out.println(om.writeValueAsString(listMap)); } }
运行结果
二、从数据库拿值然后显示到菜单并且具有层级关系