【问题标题】:Obtain Specific values from challonge.com json file into ArrayList using gson使用 gson 从 challonge.com json 文件中获取特定值到 ArrayList
【发布时间】:2015-11-17 07:27:49
【问题描述】:

我正在尝试从 challonge.com 的 JSON 文件中获取特定值(更多信息请参见 http://api.challonge.com/v1/documents/participants/index)。我试图获得的值是“id”和“name”。

这是我当前的代码。

  HttpClient client = HttpClients.createDefault();

  HttpGet request = new HttpGet(jsonUrl);

    try {
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        if(entity != null){
            //Allows me to search through the Participant Object using the 
            //Participant/Participants POJO
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(Participant.class, new MyDeserializer<>()).
                    create();
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), charset);

            /*Goes through seperate JSON files received from the Challonge API.
            */
            ArrayList<Participant> al = new ArrayList<>();


            Type type = new TypeToken<List<Participant>>(){}.getType();
            ArrayList<Participant> list = gson.fromJson(reader, al.getClass());

我也使用了类型变量而不是 al.getClass(),但是当我决定检查 id 和名称时,两者都会给我 java.lang.NullPointerException 的错误:

 System.out.println(list.get(0).getPlayerId() + ": " + list.get(0).getPlayerName());

这也是我的参与者课程

public class Participant {

   private String id;
   private String name;

   public String getPlayerId(){
       return id;
   }

   public String getPlayerName(){
       return name;
   }
}

这里是一些 json 代码的示例

[
  {
    "participant": {
     "active": true,
     "checked_in_at": null,
     "created_at": "2015-01-19T16:54:40-05:00",
     "final_rank": null,
     "group_id": null,
     "icon": null,
     "id": 16543993,
     "invitation_id": null,
     "invite_email": null,
     "misc": null,
     "name": "Participant #1",
     "on_waiting_list": false,
     "seed": 1,
     "tournament_id": 1086875,
     "updated_at": "2015-01-19T16:54:40-05:00",
     "challonge_username": null,
     "challonge_email_address_verified": null,
     "removable": true,
     "participatable_or_invitation_attached": false,
     "confirm_remove": true,
     "invitation_pending": false,
     "display_name_with_invitation_email_address": "Participant #1",
     "email_hash": null,
     "username": null,
     "attached_participatable_portrait_url": null,
     "can_check_in": false,
     "checked_in": false,
     "reactivatable": false
   }
 },
 {
   "participant": {
     "active": true,
     "checked_in_at": null,
     "created_at": "2015-01-19T16:54:43-05:00",
     "final_rank": null,
     "group_id": null,
     "icon": null,
     "id": 16543994,
     "invitation_id": null,
     "invite_email": null,
     "misc": null,
     "name": "Participant #2",
     "on_waiting_list": false,
     "seed": 2,
     "tournament_id": 1086875,
     "updated_at": "2015-01-19T16:54:43-05:00",
     "challonge_username": null,
     "challonge_email_address_verified": null,
     "removable": true,
     "participatable_or_invitation_attached": false,
     "confirm_remove": true,
     "invitation_pending": false,
     "display_name_with_invitation_email_address": "Participant #2",
     "email_hash": null,
     "username": null,
     "attached_participatable_portrait_url": null,
     "can_check_in": false,
     "checked_in": false,
     "reactivatable": false
      }
   }
 ]

提前感谢您的帮助!

【问题讨论】:

    标签: java json arraylist nullpointerexception gson


    【解决方案1】:

    我实际上最终找到了一种对我有用的方法。

        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(jsonUrl);
    
        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                //Allows me to search through the Participant Object using the 
                //Participant/Participants POJO
                Gson gson = new GsonBuilder().
                        registerTypeAdapter(ParticipantWrapper.class, new MyDeserializer<>()).
                        create();
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                Reader reader = new InputStreamReader(entity.getContent(), charset);
    
                /*Goes through seperate JSON files received from the Challonge API.
                */
                ArrayList<Participant> al = new ArrayList<>();
    
                JsonParser jsonParser = new JsonParser();
                JsonElement jsonElement = jsonParser.parse(reader);
    
    
               if(jsonElement.isJsonArray()){
                   Iterator itor = jsonElement.getAsJsonArray().iterator();
    
                   while(itor.hasNext()){
                       JsonObject jObject = (JsonObject) itor.next();
                       al.add(gson.fromJson(jObject.get("participant"), Participant.class));
                   }
               }
                return al;
            }
        } catch (IOException ex) {
            Logger.getLogger(TournamentInfo.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    

    【讨论】:

      【解决方案2】:

      不幸的是,您的 JSON 比 Java 对象层次结构更深一层。它不包含参与者列表,而是包含参与者的事物列表

      试试这个:

      public class ParticipantWrapper {
          public final Participant participant;
      
          public ParticipantWrapper {
              participant = null;
          }
      }
      

      然后:

       ArrayList<ParticipantWrapper> list = gson.fromJson(reader, new TypeToken<List<ParticipantWrapper>>(){}.getType());
      

      最后:

      final String id = list.get(0).participant.getPlayerId();
      

      编辑:请查看这个完整且有效的示例:https://gist.github.com/DavidMihola/2ee7740a2c0c22b016b4

      【讨论】:

      • 我认为这与此有关。我进行了更改,但我仍然继续收到 NullPointerException
      • 这很奇怪...我刚刚看到你有registerTypeAdapter(Participant.class, new MyDeserializer&lt;&gt;()) 行-MyDeserializer 做什么?你试过没有那条线吗?
      • 另外,null 是什么?清单本身?索引 0 处的项目?还是包裹在该物品中的参与者?
      • 它应该为 collection.class 注册一个类型适配器,然后将每个数组成员映射到适当的对象。我只是将其更改为 ParticipantWrapper.class ,但这也失败了,还将ArrayList&lt;ParticipantWrapper&gt; list = gson.fromJson(reader, new TypeToken&lt;List&lt;ParticipantWrapper&gt;&gt;(){}.getType()); 更改为&gt;ArrayList&lt;ParticipantWrapper&gt; list = new Gson().fromJson(reader, new TypeToken&lt;List&lt;ParticipantWrapper&gt;&gt;(){}.getType()); 但这也给了我一个空指针
      • 列表本身也是空的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多