Java递归解析任意层的Json数据,获取所有的key和value,

纯手打,转载务请附上本文网址!!!

有需要的可以自己下载看看,github代码:https://github.com/xianzhixianzhixian/JsonDemo.git

实习,需要做到几个功能:

1、从内容的Json字符串中获取所有的key和value

2、把未知的Json字符传转化为LinkedList<LinkedList<String>>类型的数据

首先我们面对的是一个未知的Json字符串,例如下面的这几串Json数据

使用的样例数据

{"title": "新增的任务的表单信息", "type": "object", "properties": {"finishTime": {"type": "number", "title": "任务结束时间例如:1450708950086"}, "contactEmail": {"type": "string", "title": "联系人邮箱"}, "sexType": {"type": "string", "title": "招聘性别要求,FEMALE:女,MALE:男,UNKWON:男女不限"}, "enrollEndTime": {"type": "number", "title": "报名截止时间例如:1450708950086"}, "description": {"type": "string", "title": "备注"}, "weekday": {"type": "string", "title": "工作日期"}, "title": {"type": "string", "title": "任务标题"}, "startTime": {"type": "number", "title": "任务开始时间,例如:1450708950086"}, "contactTelephone": {"type": "string", "title": "联系人电话"}, "timeDescription": {"type": "string", "title": "工作时间描述"}, "paymentType": {"type": "string", "title": "支付类型 0:线上支付,1:线下支付"}, "addressList": {"items": {"properties": {"latitude": {"type": "string", "title": "纬度"}, "cityName": {"type": "string", "title": "城市名称"}, "areaName": {"type": "string", "title": "区域名称"}, "longitude": {"type": "string", "title": "经度"}, "address": {"type": "string", "title": "t工作地点"}}, "type": "object", "description": "任务地址"}, "type": "array", "title": "地址列表"}, "balanceUnit": {"type": "string", "title": "兼职金额单位;例如:元/小时,元/天等"}, "contactName": {"type": "string", "title": "联系人姓名"}, "content": {"type": "string", "title": "工作内容"}, "balance": {"type": "number", "title": "兼职金额"}, "headcount": {"type": "integer", "title": "招聘人数"}, "typeDesc": {"type": "string", "title": "任务类型描述: 只有在任务类型为其他时有效"}, "type": {"type": "string", "title": "任务类型;例如:传单派发,服务员等"}, "balanceType": {"type": "integer", "title": "结算类型;例如:完工结,日结等"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"items": {"type": "string"}, "type": "array"}

{"type": "object", "properties": {}}

那我们要怎样去递归的获取其中所有的key和value呢?这时候JsonPath已经不起作用了,我们需要用原生的Json解析才行

1、pom文件的配置,所用到的jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yufeng.json</groupId>
    <artifactId>JsonDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier><!-- 指定jdk版本 -->
        </dependency>
    </dependencies>
</project>

2、程序的代码准备

递归读取未知Json字符串中所有的key和value,将其转化为LinkedList<LinkedList<String>>类型的数据

package com.yufeng.json;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Json工具类
 * 钰丰 2018/2/5
 */
public class JsonUtil {

    public static List<String> list=new LinkedList<String>();

    /**
     * 递归读取所有的key,某些限制可以自己除去,核心部分
     * @param jsonObject
     */
    public static void getAllKey(JSONObject jsonObject){
        Iterator<String> keys=jsonObject.keys();
        while(keys.hasNext()){
            String key=keys.next();
            if(isJsonObject(jsonObject.get(key).toString())){
                if(!key.equals("properties") && !isArrayOrObject(jsonObject.get(key).toString())) {
                    System.out.println(key);
                }
                JSONObject innerObject=JSONObject.fromObject(jsonObject.get(key));
                getAllKey(innerObject);
            }
        }
    }

    /**
     * 从未知的JsonArray中获取LinkedList
     * @return
     */
    public static LinkedList<LinkedList<String>> getLinkedListFromJsonArray(String jsonArrayStr){

        LinkedList<LinkedList<String>> linkedList=null;
        if(jsonArrayStr!=null && jsonArrayStr.length()>0){
            JSONArray jsonArray=JSONArray.fromObject(jsonArrayStr);
            linkedList=new LinkedList<LinkedList<String>>();
            for(int i=0;i<jsonArray.size();i++){
                JSONArray array=JSONArray.fromObject(jsonArray.get(i));
                LinkedList<String> internalList=new LinkedList<String>();
                for(int j=0;j<array.size();j++){
                    internalList.add(array.get(j).toString());
                }
                linkedList.add(internalList);
            }
        }
        return linkedList;
    }

    /**
     * 判断某个Json字符串是否为一个标准的Json字符串
     * @param jsonString
     * @return
     */
    public static Boolean isJsonObject(String jsonString){
        try{
            JSONObject.fromObject(jsonString);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 判断某个Json字符串是否为一个Json数组
     * @param jsonObject
     * @return
     */
    public static Boolean isArrayOrObject(String jsonObject){
        String type=JSONObject.fromObject(jsonObject).get("type").toString();
        if(type.equals("object") || type.equals("array")){
            return true;
        }else{
            return false;
        }
    }
}

/*
给getAllKey使用的数据

{"title": "新增的任务的表单信息", "type": "object", "properties": {"finishTime": {"type": "number", "title": "任务结束时间例如:1450708950086"}, "contactEmail": {"type": "string", "title": "联系人邮箱"}, "sexType": {"type": "string", "title": "招聘性别要求,FEMALE:女,MALE:男,UNKWON:男女不限"}, "enrollEndTime": {"type": "number", "title": "报名截止时间例如:1450708950086"}, "description": {"type": "string", "title": "备注"}, "weekday": {"type": "string", "title": "工作日期"}, "title": {"type": "string", "title": "任务标题"}, "startTime": {"type": "number", "title": "任务开始时间,例如:1450708950086"}, "contactTelephone": {"type": "string", "title": "联系人电话"}, "timeDescription": {"type": "string", "title": "工作时间描述"}, "paymentType": {"type": "string", "title": "支付类型 0:线上支付,1:线下支付"}, "addressList": {"items": {"properties": {"latitude": {"type": "string", "title": "纬度"}, "cityName": {"type": "string", "title": "城市名称"}, "areaName": {"type": "string", "title": "区域名称"}, "longitude": {"type": "string", "title": "经度"}, "address": {"type": "string", "title": "t工作地点"}}, "type": "object", "description": "任务地址"}, "type": "array", "title": "地址列表"}, "balanceUnit": {"type": "string", "title": "兼职金额单位;例如:元/小时,元/天等"}, "contactName": {"type": "string", "title": "联系人姓名"}, "content": {"type": "string", "title": "工作内容"}, "balance": {"type": "number", "title": "兼职金额"}, "headcount": {"type": "integer", "title": "招聘人数"}, "typeDesc": {"type": "string", "title": "任务类型描述: 只有在任务类型为其他时有效"}, "type": {"type": "string", "title": "任务类型;例如:传单派发,服务员等"}, "balanceType": {"type": "integer", "title": "结算类型;例如:完工结,日结等"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"items": {"type": "string"}, "type": "array"}

{"type": "object", "properties": {}}
*/   
    /**
     * 核心部分
     * @param jsonObject
     */
    public static void getAllKey(JSONObject jsonObject){
        Iterator<String> keys=jsonObject.keys();
        while(keys.hasNext()){
            String key=keys.next();
            if(isJsonObject(jsonObject.get(key).toString())){
                if(!key.equals("properties") && !isArrayOrObject(jsonObject.get(key).toString())) {
                    System.out.println(key);
                }
                JSONObject innerObject=JSONObject.fromObject(jsonObject.get(key));
                getAllKey(innerObject);
            }
        }
    }

    /**
     * 从未知的JsonArray中获取LinkedList
     * @return
     */
    public static LinkedList<LinkedList<String>> getLinkedListFromJsonArray(String jsonArrayStr){

        LinkedList<LinkedList<String>> linkedList=null;
        if(jsonArrayStr!=null && jsonArrayStr.length()>0){
            JSONArray jsonArray=JSONArray.fromObject(jsonArrayStr);
            linkedList=new LinkedList<LinkedList<String>>();
            for(int i=0;i<jsonArray.size();i++){
                JSONArray array=JSONArray.fromObject(jsonArray.get(i));
                LinkedList<String> internalList=new LinkedList<String>();
                for(int j=0;j<array.size();j++){
                    internalList.add(array.get(j).toString());
                }
                linkedList.add(internalList);
            }
        }
        return linkedList;
    }

    /**
     * 判断某个Json字符串是否为一个标准的Json字符串
     * @param jsonString
     * @return
     */
    public static Boolean isJsonObject(String jsonString){
        try{
            JSONObject.fromObject(jsonString);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 判断某个Json字符串是否为一个Json数组
     * @param jsonObject
     * @return
     */
    public static Boolean isArrayOrObject(String jsonObject){
        String type=JSONObject.fromObject(jsonObject).get("type").toString();
        if(type.equals("object") || type.equals("array")){
            return true;
        }else{
            return false;
        }
    }
}

/*
给getAllKey使用的数据

{"title": "新增的任务的表单信息", "type": "object", "properties": {"finishTime": {"type": "number", "title": "任务结束时间例如:1450708950086"}, "contactEmail": {"type": "string", "title": "联系人邮箱"}, "sexType": {"type": "string", "title": "招聘性别要求,FEMALE:女,MALE:男,UNKWON:男女不限"}, "enrollEndTime": {"type": "number", "title": "报名截止时间例如:1450708950086"}, "description": {"type": "string", "title": "备注"}, "weekday": {"type": "string", "title": "工作日期"}, "title": {"type": "string", "title": "任务标题"}, "startTime": {"type": "number", "title": "任务开始时间,例如:1450708950086"}, "contactTelephone": {"type": "string", "title": "联系人电话"}, "timeDescription": {"type": "string", "title": "工作时间描述"}, "paymentType": {"type": "string", "title": "支付类型 0:线上支付,1:线下支付"}, "addressList": {"items": {"properties": {"latitude": {"type": "string", "title": "纬度"}, "cityName": {"type": "string", "title": "城市名称"}, "areaName": {"type": "string", "title": "区域名称"}, "longitude": {"type": "string", "title": "经度"}, "address": {"type": "string", "title": "t工作地点"}}, "type": "object", "description": "任务地址"}, "type": "array", "title": "地址列表"}, "balanceUnit": {"type": "string", "title": "兼职金额单位;例如:元/小时,元/天等"}, "contactName": {"type": "string", "title": "联系人姓名"}, "content": {"type": "string", "title": "工作内容"}, "balance": {"type": "number", "title": "兼职金额"}, "headcount": {"type": "integer", "title": "招聘人数"}, "typeDesc": {"type": "string", "title": "任务类型描述: 只有在任务类型为其他时有效"}, "type": {"type": "string", "title": "任务类型;例如:传单派发,服务员等"}, "balanceType": {"type": "integer", "title": "结算类型;例如:完工结,日结等"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"type": "object", "properties": {"arg0": {"type": "string", "description": "", "title": ""}, "arg1": {"title": "", "type": "integer", "description": "", "format": "int32"}, "arg2": {"title": "", "type": "integer", "description": "", "format": "int64"}}}

{"items": {"type": "string"}, "type": "array"}

{"type": "object", "properties": {}}
*/

3、运行代码及结果展示

public class JsonDemo {

    public static void main(String[] args){
        JSONObject jsonObject=JSONObject.fromObject("{\"title\": \"新增的任务的表单信息\", \"type\": \"object\", \"properties\": {\"finishTime\": {\"type\": \"number\", \"title\": \"任务结束时间例如:1450708950086\"}, \"contactEmail\": {\"type\": \"string\", \"title\": \"联系人邮箱\"}, \"sexType\": {\"type\": \"string\", \"title\": \"招聘性别要求,FEMALE:女,MALE:男,UNKWON:男女不限\"}, \"enrollEndTime\": {\"type\": \"number\", \"title\": \"报名截止时间例如:1450708950086\"}, \"description\": {\"type\": \"string\", \"title\": \"备注\"}, \"weekday\": {\"type\": \"string\", \"title\": \"工作日期\"}, \"title\": {\"type\": \"string\", \"title\": \"任务标题\"}, \"startTime\": {\"type\": \"number\", \"title\": \"任务开始时间,例如:1450708950086\"}, \"contactTelephone\": {\"type\": \"string\", \"title\": \"联系人电话\"}, \"timeDescription\": {\"type\": \"string\", \"title\": \"工作时间描述\"}, \"paymentType\": {\"type\": \"string\", \"title\": \"支付类型 0:线上支付,1:线下支付\"}, \"addressList\": {\"items\": {\"properties\": {\"latitude\": {\"type\": \"string\", \"title\": \"纬度\"}, \"cityName\": {\"type\": \"string\", \"title\": \"城市名称\"}, \"areaName\": {\"type\": \"string\", \"title\": \"区域名称\"}, \"longitude\": {\"type\": \"string\", \"title\": \"经度\"}, \"address\": {\"type\": \"string\", \"title\": \"t工作地点\"}}, \"type\": \"object\", \"description\": \"任务地址\"}, \"type\": \"array\", \"title\": \"地址列表\"}, \"balanceUnit\": {\"type\": \"string\", \"title\": \"兼职金额单位;例如:元/小时,元/天等\"}, \"contactName\": {\"type\": \"string\", \"title\": \"联系人姓名\"}, \"content\": {\"type\": \"string\", \"title\": \"工作内容\"}, \"balance\": {\"type\": \"number\", \"title\": \"兼职金额\"}, \"headcount\": {\"type\": \"integer\", \"title\": \"招聘人数\"}, \"typeDesc\": {\"type\": \"string\", \"title\": \"任务类型描述: 只有在任务类型为其他时有效\"}, \"type\": {\"type\": \"string\", \"title\": \"任务类型;例如:传单派发,服务员等\"}, \"balanceType\": {\"type\": \"integer\", \"title\": \"结算类型;例如:完工结,日结等\"}}}");
        JsonUtil.getAllKey(jsonObject);

    }
}

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值