java - 如何获取 json 文件中的每个 json 元素并将它们放入数组中

标签 java arrays json

[
  {
    "origin": "12345",
    "destination": "2345",
    "time": 37,
    "days": "37",
    "people": "45"
  },
  {
    "origin": "34562",
    "destination": "12341",
    "time": 28,
    "days": "27",
    "people": "99"
  },
  {
    "origin": "84532",
    "destination": "35521",
    "time": 40,
    "days": "17",
    "people": "39"
  },
  {
    "origin": "12312",
    "destination": "75435",
    "time": 17,
    "days": "17",
    "people": "35"
  },
...
]

我想获取json文件中的每个json对象并将它们放入一个数组中。 所以我需要一个“origin”字符串数组,“destination”字符串数组,“time”int数组,“days”字符串数组和一个“people”字符串数组。

由于“[”,我开始这样,并尝试了很多方法来获取每个元素,但我无法获取 json.file 中的每个元素

public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File(dirPath + "move.json");
        try {
            String content = new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
            JSONObject json = new JSONObject(content.substring(4));

谢谢

最佳答案

基本上,您必须创建一个映射,映射的键就是 JSON 对象中的键。 在 JSON 数组中进行迭代时,您可以将每个键值附加到已创建的映射中

public class App 
{
    public static void main( String[] args ) throws Exception
    {
        File file = new File("input.json");
        String content = new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
        JSONArray array = new JSONArray(content); //parse your string data to JSON Array
        Map<String, List<Object>> map = new HashMap<>(); //create a HashMap having a key type as String and values as List of Object, 
        //since you are creating array for each key
        for(int i=0; i<array.length(); i++) //looping on all JSON Objects
        {
            JSONObject obj = array.getJSONObject(i);
            for (String key : obj.keySet()) { //looping on all keys in each JSON Object
                if(map.get(key) == null)
                    map.put(key, new ArrayList<Object>()); //initializing the list for the 1st use
                map.get(key).add(obj.get(key));//adding the value to the list of the corresponding key
            }
        }

        //Output:
        for (String key : map.keySet()) {
            System.out.println(key);
            System.out.println(map.get(key));
        }
    }
}

输出将是:

origin
[12345, 34562, 84532, 12312]
destination
[2345, 12341, 35521, 75435]
days
[37, 27, 17, 17]
time
[37, 28, 40, 17]
people
[45, 99, 39, 35]

关于java - 如何获取 json 文件中的每个 json 元素并将它们放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57626635/

相关文章:

java - 测试用例未按照 TestNG xml 中测试类名称的顺序定义执行

java - 所有数字的总和,直到它在具有 o(1) 复杂度的 Java 中变成单个数字?

java - 为什么 String 列表没有 forEach 方法?

javascript - 将 JSON 字符串传递给 PHP 并推送到数组

Android json解析存入数据库

php - 如何根据 JSON API 响应创建自动建议?

java - Spring Boot + WEB-INF

Java使用notepad++和nppexec编译运行

java - 从 Java Servlet 返回字符串数组到 jQuery

JSON 的 Javascript 表单序列化