在Java中读取json文件中的json对象数组的属性 [英] Read properties of array of json objects in a json file in java

查看:1000
本文介绍了在Java中读取json文件中的json对象数组的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的JSON数组/对象是陌生的.在这里,我在努力获取JSON对象的属性.我的尝试如下.

I am new to JSON array/objects in the java. Here I am struggling to get the property of a JSON object. My attempt is as follows.

    JSONParser jsonParser = new JSONParser();
    try(FileReader reader = new FileReader("players.json")){                                     
       //Read JSON file                                  
       Object obj = jsonParser.parse(reader);                                                                
       JSONArray playersList = (JSONArray) obj; 
       //Below is the one which is having compilation issues                                                                 
       System.out.println(playersList.get(1).getString("name")); 

    } catch (FileNotFoundException e) {                                  
       // TODO Auto-generated catch block

           e.printStackTrace();
    } catch (IOException e) {                                    
       // TODO Auto-generated catch block

          e.printStackTrace();
     } catch (ParseException e) {                                    
       // TODO Auto-generated catch block                                    
          e.printStackTrace();
    }

我正在尝试获取JSON数组中第二个对象的名称.但是我找不到如上所述的调用getString("name")的方法.因此,我非常感谢您为此提供的帮助.

There I am trying to get the name of the second object in the JSON array. But I couldn't find a way to call getString("name") as above. So I highly appreciate your help for this.

Json文件如下.

      [
       {
         "_id": 1, 
         "name": "greg",
       },
       {
         "_id": 2,   
         "name": "freg gre",
       }
      ]

推荐答案

您可以按照以下方式使用

You can use like following

  JSONObject jsonObject = (JSONObject)playersList.get(1);
  String name = (String) jsonObject.get("name");

这篇关于在Java中读取json文件中的json对象数组的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆