使用 java 访问 JSON 属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17012955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:43:16  来源:igfitidea点击:

Accessing JSON property name using java

javajson

提问by canadiancreed

I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows:

我正在研究一种解析 JSON 文件并收集其内容以供其他地方使用的方法。我目前有一个工作示例,如下所示:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class testJSONParser {
    public static void main(String[] args) throws Exception {
        List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();

        BufferedReader br = new BufferedReader(new FileReader("json.txt"));

        try {
            String line = br.readLine();

            while (line != null) {
                JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);

                Map<String, String> currentLineMap = new HashMap<String, String>();

                currentLineMap.put("country", jsonObject.get("country").toString());
                currentLineMap.put("size", jsonObject.get("size").toString());
                currentLineMap.put("capital", jsonObject.get("capital").toString());

                jsonArray.add(currentLineMap);

                line = br.readLine();
            }
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                br.close();
            };
        }
    }
}

I'm using the json simplelibrary for parsing the passed in JSON strings.

我正在使用json 简单库来解析传入的 JSON 字符串。

Here's a sample string from the parsed file.

这是来自解析文件的示例字符串。

{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}

What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have:

我的问题是如何获取这段代码,并让 put 方法能够动态分配给相应的 Map。这是我目前拥有的:

for (int i = 0; i < jsonObject.size(); i++) {
     currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}

The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?

这 ???部分是我难倒的地方。获取当前 JSON 行的值很容易。但是如何获取属性值(在 JSON 字符串示例中以粗体突出显示)让我难以理解。有没有我可以调用这个我不熟悉的对象的方法?一种不同的更好的方法来遍历这个?还是我从一开始就完全在做这件事?

回答by Jan Doerrenhaus

In the JSON.org reference implementation, you could do:

在 JSON.org 参考实现中,您可以执行以下操作:

for (String key : JSONObject.getNames(jsonObject))
{
    map.put(key, jsonObject.get(key));
}

In JSON simple, you would do:

在简单的 JSON 中,你会这样做:

for (Object keyObject : jsonObject.keySet())
{
    String key = (String)keyObject;
    map.put(key, (String)jsonObject.get(key));
}

This should do the trick.

这应该可以解决问题。