Java recursively implements a method for dynamically parsing unknown keys in json strings

There are times when we need to parse unknown json. Or dynamic json. Then we don't know how many keys are, or the keys are not fixed. At this time, you need to parse the dynamic key method.

This method is what I need when parsing the incoming json in the foreground. Because the front-end of each interface is json is not fixed. If you really parse the data sent by each page once, it will be too troublesome. So a general analysis method is needed. Parse it into a map. Then you only need to call this method to get the map of the json passed in the foreground.

After a while on the Internet, I can't find the method I want, that is, it doesn't agree with me, and the code is not complete. So I tested a simple code myself. I implemented it using recursion and the code is simple. I will not explain them one by one, if there is still something unclear, please leave a message.

package jsonTest;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

public class JsonTest {
    public static void main(String[] args) {
        //测试字符串
        String test = "{a:1,b:2,c:3,d:{q:4,w:5,e:6,y:{o:7,p:8}}}";
        Map res = new HashMap();
        //递归遍历解析方法
        iteraJson(test,res);
        //解析得到最终map后,遍历该map输出值
        Set keySet = res.keySet();
        Iterator iterator = keySet.iterator();
        while(iterator.hasNext()){
            String key = iterator.next().toString();
            Object val = res.get(key);
            System.out.println(key+":"+val.toString());
        }
    }
    //递归遍历解析方法
    public static boolean iteraJson(String String,Map res){
      //因为json串中不一定有逗号,但是一定有:号,所以这里判断没有则已经value了
        if(String.toString().indexOf(":") == -1){
            return true;
        }
        JSONObject fromObject = JSONObject.fromObject(String);
        Iterator keys = fromObject.keys();
        while(keys.hasNext()){
            String key = keys.next().toString();
            Object value = fromObject.get(key);
            if(iteraJson(value.toString(),res)){
                res.put(key, value);
            }
        }
        return false;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325615278&siteId=291194637