java如何向类添加json列表

iszxjhcz  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(216)

我试图将从api端点接收的jsonMap到我创建的类,但是当我使用get命令时,我得到的是null。我不知道为什么?我不认为我已经正确地Map了类,但是对于接收到的json的布局,我不太确定如何正确地Map它。我将收到的json格式如下:

{1 item
 "matches":[10 items
  0:{3 items
   "when":"Friday, Aug 09 2019 20:00"
    "team1":{1 item
    "teamName":"Liverpool"
              }
    "team2":{1 item
         "teamName":"Norwich"
            }
           }
      1:{3 items
   "when":"Saturday, Aug 10 2019 12:30"
 "team1":{1 item
 "teamName":"West Ham"
 }
   "team2":{1 item
  "teamName":"Manchester City"
    }
 }
  2:{3 items
   "when":"Saturday, Aug 10 2019 15:00"
    "team1":{1 item
      "teamName":"Bournemouth"
      }
      "team2":{1 item
      "teamName":"Sheffield United"
      }
    }

我创建的当前类是:

@JsonIgnoreProperties
public class Matches {
private String when;
private String referee;
private List<Matches> team1;
private List<Matches> team2;
private String time;
private String venue;
private String attendance;
public String getWhen() {
    return when;
}
public void setWhen(String when) {
    this.when = when;
}
public List<Matches> getTeam1() {
    return team1;
}
public void setTeam1(List<Matches> team1) {
    this.team1 = team1;
}
public List<Matches> getTeam2() {
    return team2;
}
public void setTeam2(List<Matches> team2) {
    this.team2 = team2;
}}

控制器代码:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("URL")
    .get()
    .addHeader("x-rapidapi-key", "KEY")
    .addHeader("x-rapidapi-host", "HOST")
    .build();

Response response = client.newCall(request).execute();
String responseBodyString = response.body().string();
System.out.println(responseBodyString);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Matches bean = objectMapper.readValue(responseBodyString, Matches.class);
System.out.println("Name: " +bean.getWhen());

有人知道我如何将这个jsonMap到我的类,这样我就可以使用它提取的数据了吗?干杯,杰夫

x7rlezfr

x7rlezfr1#

json码:

{
   "matches":[
      {
         "when":"Friday, Aug 09 2019 20:00",
         "team1":{
            "teamName":"Liverpool"
         },
         "team2":{
            "teamName":"Norwich"
         }
      },
      {
         "when":"Saturday, Aug 10 2019 12:30",
         "team1":{
            "teamName":"West Ham"
         },
         "team2":{
            "teamName":"Manchester City"
         }
      },
      {
         "when":"Saturday, Aug 10 2019 15:00",
         "team1":{
            "teamName":"Bournemouth"
         },
         "team2":{
            "teamName":"Sheffield United"
         }
      }
}

java 语:

class Team {
    String teamName;
}
class Match {
    Date when;
    Team team1;
    Team team2;
}
class Response {
    List<Match> matches;
}

response bean=objectmapper.readvalue(responsebodystring,response.class);

相关问题