本文介绍Java中解析JSON的一种方法,可以让我们在Java程序中也用x.x.x的形式访问JSON数据中的值。
代码大部分来源非本人,本人在源代码基础上加以修改以使正常运行。
代码:
// 将提取方法进行封装成方法 方便调用
@SuppressWarnings("unchecked")
public static Object getKeyJsonQuery(Map<?,?> map ,String jsonKey){
String[] arrs = jsonKey.split("\.");
Object obj = null;
for(int i=0;i<arrs.length;i++){
if(i==0) {
obj = handle(map, arrs[i]);
}else{
if(obj instanceof Map){
obj = handle((Map<?, ?>) obj,arrs[i]);
}else if(obj instanceof List){
obj = handle((List<Map<?, ?>>) obj,arrs[i]);
}
}
}
return obj;
}
//解析map类型的对象
public static Object handle(Map<?,?> map,String key){
return map.get(key);
}
// 解析list类型的对象
@SuppressWarnings("unchecked")
public static Object handle(List<Map<?,?>> listMap,String key){
List<Map<String,Object>> listMaps = new ArrayList<>();
List<Object> lists = new ArrayList<>();
// 这里用到了java8的一个新特性 stream 流
listMap.stream().filter(e->null !=e.get(key) ).forEach(e->{
//表示既不是map 又不是list类型
if(!(e.get(key) instanceof Map<?,?>) && !(e.get(key) instanceof List<?>) ) {
lists.add(e.get(key));
}else{
listMaps.addAll((Collection<? extends Map<String, Object>>) e.get(key));
}
});
return lists.size()>0 && !lists.isEmpty() ? lists:listMaps;
}
public static void main(String[] args) throws Exception {
String json = "{"data":{"order":[{"money":"15","orders":[{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"2"},{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"3"}]},{"money":"16","orders":[{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"2"},{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"3"}]},{"money":"17","orders":[{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"2"},{"b1":[{"bc1":"1","bc2":"2"},{"bc1":"2","bc2":"3"}],"b2":"3"}]}],"info":{"record":[{"a1":"1","a2":"2"},{"a1":"1","a2":"2"},{"a1":"1","a2":"2"}]}},"time":{"addr":"123","num":{"a":"111","b":"222"}}}";
Gson gson = new Gson();
@SuppressWarnings("unchecked")
Map<String,Object> map = gson.fromJson(json, Map.class);
System.out.println(map.toString());
String jsonKey = "data.order.money";
//String jsonKey = "time.num.a";
//String jsonKey ="data.info";
Object obj = getKeyJsonQuery(map,jsonKey);
System.out.println(obj.toString());
}
---------------------
作者:YancyMauno
来源:CSDN
原文:https://blog.csdn.net/ITmaotongxue/article/details/83013769?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!