0

次のコードを使用してファイルから JSON データを取得しています。現在、JSON を 1 つの文字列で取得できました。それを配列に解析したい。json ファイルは次のようになります。

{
    "employee": [
        {
            "name": "joan",
            "lastname": "test",
            "age": 23
        },

次のコードを使用してデータを取得していますが、1 つの文字列で取得し、データの一部を印刷したい

JSONObject jsonObject = (JSONObject) parser
                .parse(new FileReader("C:\\MockData\\Json\\js.txt"));

        JSONParser parser1 = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            public List<?> creatArrayContainer() {
                return new LinkedList<Object>();
            }

            public Map<?, ?> createObjectContainer() {
                return new LinkedHashMap<Object, Object>();
            }

        };

        Map<?, ?> json = (Map<?, ?>) parser1.parse(jsonObject.toJSONString(), containerFactory);

        Iterator<?> iter = json.entrySet().iterator();
        System.out.println("==iterate result==");

        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();

            System.out.println(entry.getKey() + "=>" + entry.getValue());

        }

これが出力です

employee=[{age=23, name=joan, lastname=test}, {age=22, name=Alex, lastname=avz}, {age=65, name=Dan, lastname=severn}]

ここで、entry.getValue() は、配列の 1 つの連結された文字列を返します。whileは 1 回だけ実行されます...しかし、キー値を取得するためにループしたいと思います。どうすればいいですか?たとえば、 22歳のアレックスという名前を印刷したい場合、どうすればよいですか?

:ファイルを変更できるため、キーがわかりません(現在はその名前ですが、firstNameおよびその他のフィールドにすることができます。そのための一般的なソリューションが必要です)。

それを行うことができる別のパーサーを使用する方法があれば、私は開いています。

4

2 に答える 2

2

The following is the full solution to your question. With this code you can break down the data to each employee and also separate the employee attributes.

 Set<String> keySet = jsonObject.keySet();
                Iterator keySetIterator = keySet.iterator();
                while(keySetIterator.hasNext()){
                    JSONArray array = (JSONArray)jsonObject.get(keySetIterator.next());

                        while(employeeKeySetIterator.hasNext()){
                            String employeeKey = employeeKeySetIterator.next().toString();
                            System.out.println(employeeKey + " : "+ employee.get(employeeKey));
                        }
                    }
                }
于 2013-03-05T08:59:09.623 に答える
1

内部のjson文字列をJSONArrayにキャストする必要があります

JSONArray array = (JSONArray)jsonObject.get("employee");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next().toString());
}
于 2013-03-05T08:21:43.590 に答える