4

これは私が書いたプログラムです:

    /*
 * 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 つのトークンを取得しているのに、なぜ 1 つの文字列トークンしか取得しないのですか。

4

4 に答える 4

5

JsonObject を再帰的にトラバースして、すべてのキーを取得できます。疑似コードはこちら

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":"hello","d":4.0}} の場合、上記の関数は ["a","b","c "、"d"]

ただし、出力として ["a","c","d"] のみが必要な場合は、次のように記述できます-

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);
         }
    }
}
于 2013-01-31T07:07:40.357 に答える
2

org.json.simple ではなく org.jsonを使用した実装の 1 つを次に示します。

java を使用して Key:value の組み合わせで json のすべての一意の値を検索します。

入力 json:

{
    d: {
        results: [{
            __metadata: {
                uri:https://google.com, 
                    type: User
            },
            userId: jmarthens1,
            businessPhone: null,
            salaryProrating: null,
            empId: 2023,
            lastModifiedDateTime: Date(1458308558000 + 0000),
            finalJobRole: null,
            username: jmarthens,
            married: false,
            futureLeader: null,
            salary: 79000.0,
            jobRole: Program Manager,
            Professional Services,
            nickname: null,
            salaryLocal: null
        }]
    }
}

結果:

empId-2023
lastModifiedDateTime-Date(1458308558000+0000)
salary-79000.0
userId-jmarthens1
jobRole-Program Manager, Professional Services
type-User
uri-https://google.com
username-jmarthens

コード:

package test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TestClass {
    private static StringBuilder strOut = new StringBuilder();

    public static void main(String[] args) {

        try {
            String json = "{\"d\" : {\"results\" : [{\"__metadata\" : {\"uri\" : \"https://apisalesdemo8.successfactors.com:443/odata/v2/User('jmarthens1')\","
                    + " \"type\" : \"SFOData.User\"}, \"userId\" : \"jmarthens1\", \"businessPhone\" : null, \"salaryProrating\" : null, \"empId\" : \"2023\", "
                    + "\"lastModifiedDateTime\" : \"Date(1458308558000+0000)\", \"finalJobRole\" : null, \"username\" : \"jmarthens\", \"married\" : false, "
                    + "\"futureLeader\" : null, \"salary\" : \"79000.0\", \"jobRole\" : \"Program Manager, Professional Services\", \"nickname\" : null, \"salaryLocal\" : null}]}}";
            JSONObject inputJson = new JSONObject(json);
            List<String> lst = new ArrayList<String>();
            lst = findKeysOfJsonObject(inputJson, lst);

            try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\temp\\temp.txt"))) {
                writer.write(strOut.toString());
            }
        } catch (JSONException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static List<String> findKeysOfJsonArray(JSONArray jsonIn, List<String> keys) {
        List<String> keysFromArr = new ArrayList<>();

        if (jsonIn != null && jsonIn.length() != 0) {
            for (int i = 0; i < jsonIn.length(); i++) {
                JSONObject jsonObjIn = jsonIn.getJSONObject(i);
                keysFromArr = findKeysOfJsonObject(jsonObjIn, keys);
            }
        }

        return keysFromArr;
    }

    private static List<String> findKeysOfJsonObject(JSONObject jsonIn, List<String> keys) {

        Iterator<String> itr = jsonIn.keys();
        List<String> keysFromObj = makeList(itr);
        keys.addAll(keysFromObj);

        itr = jsonIn.keys();
        while (itr.hasNext()) {
            String itrStr = itr.next();
            // System.out.println("out " + itrStr);
            JSONObject jsout = null;
            JSONArray jsArr = null;
            if (jsonIn.get(itrStr).getClass() == JSONObject.class) {
                jsout = jsonIn.getJSONObject(itrStr);
                findKeysOfJsonObject(jsout, keys);
            } else if (jsonIn.get(itrStr).getClass() == JSONArray.class) {
                jsArr = jsonIn.getJSONArray(itrStr);
                keys.addAll(findKeysOfJsonArray(jsArr, keys));
            } else if (jsonIn.get(itrStr).getClass() == String.class) {
                System.out.println(itrStr + "-" + jsonIn.get(itrStr));
                strOut.append(itrStr + "," + jsonIn.get(itrStr));
                strOut.append(System.lineSeparator());
            }
        }
        return keys;
    }

    public static List<String> makeList(Iterator<String> iter) {
        List<String> list = new ArrayList<String>();
        while (iter.hasNext()) {
            list.add(iter.next());
        }
        return list;
    }
}
于 2016-07-12T15:39:03.637 に答える