JSON выпуск в Java - PullRequest
       3

JSON выпуск в Java

0 голосов
/ 11 июля 2020

У меня есть простой JSON вывод, который выглядит как

"api":{"results":1,"predictions":[{"match_winner":"1","under_over":null,"goals_home":"-3.5","goals_away":"-1.5","advice":"Winner : Paris Saint Germain","winning_percent":{"home":"50%","draws":"50%","away":"0%"},"teams":{"home":{"team_id":85,"team_name":"Paris Saint Germain","last_5_matches":{"forme":"75%","att":"71%","def":"86%","goals":10,"goals_avg":2.5,"goals_against":2,"goals_against_avg":0.5},"all_last_matches":{"matchs":{"matchsPlayed":{"home":2,"away":2,"total":4},"wins":{"home":2,"away":1,"total":3},"draws":{"home":0,"away":0,"total":0},"loses":{"home":0,"away":1,"total":1}},"goals":{"goalsFor":{"home":7,"away":3,"total":10},"goalsAgainst":{"home":0,"away":2,"total":2}},"goalsAvg":{"goalsFor":{"home":"3.5","away":"1.5","total":"2.5"},"goalsAgainst":{"home":"0.0","away":"1.0","total":"0.5"}}},"last_h2h":{"played":{"home":4,"away":3,"total":7},"wins":{"home":3,"away":1,"total":4},"draws":{"home":1,"away":1,"total":2},"loses":{"home":0,"away":1,"total":1}}},"away":{"team_id":95,"team_name":"Strasbourg","last_5_matches":{"forme":"25%","att":"21%","def":"64%","goals":3,"goals_avg":0.75,"goals_against":5,"goals_against_avg":1.25},"all_last_matches":{"matchs":{"matchsPlayed":{"home":3,"away":1,"total":4},"wins":{"home":0,"away":0,"total":0},"draws":{"home":2,"away":1,"total":3},"loses":{"home":1,"away":0,"total":1}},"goals":{"goalsFor":{"home":3,"away":0,"total":3},"goalsAgainst":{"home":5,"away":0,"total":5}},"goalsAvg":{"goalsFor":{"home":"1.0","away":"0.0","total":"0.8"},"goalsAgainst":{"home":"1.7","away":"0.0","total":"1.3"}}},"last_h2h":{"played":{"home":3,"away":4,"total":7},"wins":{"home":1,"away":0,"total":1},"draws":{"home":1,"away":1,"total":2},"loses":{"home":1,"away":3,"total":4}}}},"h2h":[{"fixture_id":35755,"league_id":22,"league":{"name":"Ligue 1","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2017-12-02T16:00:00+00:00","event_timestamp":1512230400,"firstHalfStart":1512230400,"secondHalfStart":1512234000,"round":"Regular Season - 16","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Stade de la Meinau","referee":"Ruddy Buquet, France","homeTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"awayTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"goalsHomeTeam":2,"goalsAwayTeam":1,"score":{"halftime":"1-1","fulltime":"2-1","extratime":null,"penalty":null}},{"fixture_id":121334,"league_id":434,"league":{"name":"Coupe de la Ligue","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/65.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2017-12-13T20:05:00+00:00","event_timestamp":1513195500,"firstHalfStart":1513195500,"secondHalfStart":1513199100,"round":"8th Finals","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Stade de la Meinau (Strasbourg)","referee":null,"homeTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"awayTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"goalsHomeTeam":2,"goalsAwayTeam":4,"score":{"halftime":"1-2","fulltime":"2-4","extratime":null,"penalty":null}},{"fixture_id":35656,"league_id":22,"league":{"name":"Ligue 1","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2018-02-17T16:00:00+00:00","event_timestamp":1518883200,"firstHalfStart":1518883200,"secondHalfStart":1518886800,"round":"Regular Season - 26","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Parc des Princes","referee":"Thomas Leonard, France","homeTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"awayTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"goalsHomeTeam":5,"goalsAwayTeam":2,"score":{"halftime":"3-1","fulltime":"5-2","extratime":null,"penalty":null}},{"fixture_id":37712,"league_id":4,"league":{"name":"Ligue 1","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2018-12-05T20:00:00+00:00","event_timestamp":1544040000,"firstHalfStart":1544040000,"secondHalfStart":1544043600,"round":"Regular Season - 16","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Stade de la Meinau","referee":"Antony Gautier, France","homeTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"awayTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"goalsHomeTeam":1,"goalsAwayTeam":1,"score":{"halftime":"1-0","fulltime":"1-1","extratime":null,"penalty":null}},{"fixture_id":121449,"league_id":436,"league":{"name":"Coupe de France","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/66.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2019-01-23T20:05:00+00:00","event_timestamp":1548273900,"firstHalfStart":1548273900,"secondHalfStart":1548277500,"round":"16th Finals","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Parc des Princes","referee":"Johan Hamel, France","homeTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"awayTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"goalsHomeTeam":2,"goalsAwayTeam":0,"score":{"halftime":"1-0","fulltime":"2-0","extratime":null,"penalty":null}},{"fixture_id":37860,"league_id":4,"league":{"name":"Ligue 1","country":"France","logo":"https:\/\/media.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media.api-sports.io\/flags\/fr.svg"},"event_date":"2019-04-07T19:00:00+00:00","event_timestamp":1554663600,"firstHalfStart":1554663600,"secondHalfStart":1554667200,"round":"Regular Season - 31","status":"Match Finished","statusShort":"FT","elapsed":90,"venue":"Parc des Princes","referee":"Thomas Leonard, France","homeTeam":{"team_id":85,"team_name":"Paris Saint Germain","logo":"https:\/\/media.api-sports.io\/football\/teams\/85.png"},"awayTeam":{"team_id":95,"team_name":"Strasbourg","logo":"https:\/\/media.api-sports.io\/football\/teams\/95.png"},"goalsHomeTeam":2,"goalsAwayTeam":2,"score":{"halftime":"1-2","fulltime":"2-2","extratime":null,"penalty":null}}],"comparison":{"forme":{"home":"75%","away":"25%"},"att":{"home":"77%","away":"23%"},"def":{"home":"71%","away":"29%"},"fish_law":{"home":"0%","away":"0%"},"h2h":{"home":"85%","away":"15%"},"goals_h2h":{"home":"67%","away":"33%"}}}]}}

Код, который я написал для чтения массива teams, выглядит следующим образом:

    String json = response.body().string();
    JSONObject obj = new JSONObject(json);
    String api = obj.getString("api");
    JSONObject object2 = new JSONObject(api);
    String first = object2.getString("teams");

    System.out.println(first);

Ошибка Я получаю, что JSONObject["api"] not a string. Кто-нибудь, пожалуйста, дайте мне знать, как это читать. Я новичок в Java.

Ответы [ 3 ]

0 голосов
/ 11 июля 2020

Переход к JSONObject Я предполагаю, что вы используете org. json

В любом случае "api" - это ключ json, который не соответствует String, но вместо этого сопоставляется с вложенным json или JSONObject на языке библиотеки.

Вместо этого вам нужно сделать obj.getJSONObject("api"). То же самое для teams.

Вы должны использовать getString, getBoolean, getInt в конечных полях, таких как team_name, team_id et c.

You дополнительные примеры и полную документацию можно найти в docs .

0 голосов
/ 11 июля 2020

Ваш json текст недействителен, поэтому

final String text = "{" + json;

и

final JSONObject obj = new JSONObject(text);
final String api = obj.getString("api");
final JSONObject object2 = new JSONObject(api);
final String first = object2.getJSONArray("predictions").getJSONObject(0).getString("teams");

System.out.println(first);
0 голосов
/ 11 июля 2020

Конечно, api относится к другому объекту: {"results":1, .... Вместо этого используйте getJsonObject. См. документы .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...