本文介绍了在java中检索嵌套json中的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的程序:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 *
 * @author 311001
 */
public class NewClass {

    public static void main(String args[]) {
        JSONObject parentData = new JSONObject();
        JSONObject childData = new JSONObject();
        try {

            parentData.put("command", "login");
            parentData.put("uid", "123123123");
            childData.put("uid", "007");
            childData.put("username", "sup");
            childData.put("password", "bros");
            parentData.put("params", childData);
            System.out.println(parentData);

            Map<String, String> map = new HashMap<>();
            Iterator<?> iter = parentData.keys();
            while (iter.hasNext()) {
                String key = (String) iter.next();
                String value = parentData.getString(key);
                map.put(key, value);
            }

            for (Entry<String, String> entry : map.entrySet()) {
                System.out.println("key > " + entry.getKey() + "  : value = " + entry.getValue());
            }

            String testData = map.get("params.uid");
            System.out.println(testData);
            System.out.println("Tokenizing json");
            String resultStr = parentData.toString();
            System.out.println("String tokens ");
            StringTokenizer st = new StringTokenizer(resultStr);
            System.out.println(st.countTokens());
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
            String testDat="abc :: result";
            StringTokenizer simpleString = new StringTokenizer(testDat);
            System.out.println("Tokenizing simple string");
            System.out.println(simpleString.countTokens());
            while (simpleString.hasMoreTokens()) {
                System.out.println(simpleString.nextToken());
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

我得到的输出:

run:
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
key > uid  : value = 123123123
key > command  : value = login
key > params  : value = {"uid":"007","username":"sup","password":"bros"}
null
Tokenizing json
String tokens 
1
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
Tokenizing simple string
3
abc
::
result
BUILD SUCCESSFUL (total time: 0 seconds)

如何收到json对象中的所有键。如果我标记为什么我只得到一个字符串标记,而对于一个简单的字符串我得到正确的输出3标记。

How can I recieve all the keys in my json object. In case I tokenize why do i get only one string token while for a simple string am getting the correct output 3 tokens.

推荐答案

您可以递归遍历JsonObject以获取所有键。
继承人伪代码

You can recursively traverse your JsonObject to get all keys.heres the pseudocode

findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();
keys.addAll(keysFromObj);
for(String key:keysFromObj){
    if(obj.get(key).getClass()==JSONObject.class){
         findKeys(obj.get(key),keys);
         }
    }
}

假设您的对象是{a:1,b:{c:你好,d:4.0}}
上面的函数应该给你[a,b,c, d]

So suppose if your object is {"a":1,"b":{"c":"hello","d":4.0}}the above function should give you ["a","b","c","d"]

但是如果你只想要[a,c,d]作为输出,你可以写 -

But if you want only ["a","c","d"] as your output,you can write-

findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();

for(String key:keysFromObj){
    if(obj.get(key).getClass()==JSONObject.class){
         findKeys(obj.get(key),keys);
         }else{
         keys.add(key);
         }
    }
}

这篇关于在java中检索嵌套json中的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 19:57