我们在开发过程中经常会遇到解析Json字符串的情况,这时候采用开源工具可以快速将json字符串映射为pojo对象。而在某些业务场景中,往往为了获得json字符串中某个属性的值而不得不定义一个pojo类,从而形成与json字符串的对应。一旦json格式发生改变。pojo类也不得不作相应修改。
这时候可以考虑将json与Map映射。只要知道具体的属性名即可获取属性值。
假设有如下Json字符串
{ "id": 100, "name": "scott", "birthday": 1480785217693, "org": { "id": 1, "name": "销售部" } }
由于Json格式都是键值对形式存在,所以直接映射Map类型即可。这里采用Gson作为Json解析工具。
Gson gson = new GsonBuilder().create(); String json = "{"id":100,"name":"scott","birthday":"Dec 4, 2016 1:10:33 AM","org":{"id":1,"name":"销售部"}}"; Map map = gson.fromJson(json, Map.class);
如何取值?传统循环方式
这里用.作为属性名之间的分隔符。
-
定义解析Map的方法
private <T> T getValueByMap(String path,Map<String, Object> map,Class<T> clazz,Object defaultVal){ String[] params = path.split("\."); for(int i=0;i<params.length-1;i++){ map = (Map)map.get(params[i]); } Object result = null; result = map.get(params[params.length-1]); return result == null ? (T) defaultVal : (T) result; }
-
调用上述方法
String name = getValueByMap("org.name",map,String.class,""); System.out.println(name); double birthday = getValueByMap("birthday",map,double.class,""); System.out.println(new Double(birthday).longValue());
Ognl方式,采用该方式需引入Ognl依赖
<dependency> <groupId>ognl</groupId> <artifactId>ognl</artifactId> <version>3.1.12</version> </dependency>
代码实现
private <T> T getValueByMap(String path, Map<String, Object> map, Class<T> clazz, Object defaultVal) throws OgnlException { OgnlContext context = new OgnlContext(); context.putAll(map); Object value = Ognl.getValue(path, context); return value == null ? (T) defaultVal : (T) value; }
Json数组处理
假设json字符串如下:
{ "id": 1, "name": "销售部", "empSet": [ { "id": 2, "name": "scott 2", "birthday": 1480787444646 }, { "id": 3, "name": "scott 3", "birthday": 1480787444646 }, { "id": 4, "name": "scott 4", "birthday": 1480787444646 }, { "id": 0, "name": "scott 0", "birthday": 1480787444646 }, { "id": 1, "name": "scott 1", "birthday": 1480787444646 } ] }
-
用List与Json字符串中的数组部门映射即可。
Gson gson = new GsonBuilder().create(); String json = "{"id":1,"name":"销售部","empSet":[{"id":2,"name":"scott 2","birthday":1480787444646},{"id":3,"name":"scott 3","birthday":1480787444646},{"id":4,"name":"scott 4","birthday":1480787444646},{"id":0,"name":"scott 0","birthday":1480787444646},{"id":1,"name":"scott 1","birthday":1480787444646}]}"; Map map = gson.fromJson(json, Map.class); List emps = getValueByMap("empSet", map, List.class, ""); System.out.println(emps);