Home > Back-end >  Deserialization Json file with objectMapper in Java REST app
Deserialization Json file with objectMapper in Java REST app

Time:01-28

Hi Everyone, I hava a Json file like this:

 {
   "Events":[{
     "sport_event_id": "sr:sport_event:27636100",
     "start_date": "2021-06-22T18:00:00 00:00",
     "sport_name": "Soccer",
     "competition_name": "UEFA Champions League",
     "competition_id": "sr:competition:7",
     "season_name": "UEFA Champions League 21/22",
     "competitors": [
       {
         "id": "sr:competitor:37863",
         "name": "SS Folgore Falciano Calcio",
         "country": "San Marino",
         "country_code": "SMR",
         "abbreviation": "FFC",
         "qualifier": "home",
         "gender": "male"
       },
       {
         "id": "sr:competitor:277829",
         "name": "FC Prishtina",
         "country": "Kosovo",
         "country_code": "KOS",
         "abbreviation": "PRI",
         "qualifier": "away",
         "gender": "male"
       }
     ],
     "venue": {
       "id": "sr:venue:8329",
       "name": "Elbasan Arena",
       "capacity": 12500,
       "city_name": "Elbasan",
       "country_name": "Albania",
       "map_coordinates": "41.115875,20.091992",
       "country_code": "ALB"
     },
     "probability_home_team_winner": 2.5,
     "probability_draw": 88.1,
     "probability_away_team_winner": 9.4
   }
   ]
 } 

I would like to read the json from the file and display the contents. For Json deserialization, I created appropriate Entity,Repo and Service classes for: Competitor, Venue, Events

Venue Class:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "name",
        "capacity",
        "city_name",
        "country_name",
        "map_coordinates",
        "country_code"
})
@Entity
public class Venue implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long venueId;
    @JsonProperty("id")
    private String id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("capacity")
    private int capacity;
    @JsonProperty("city_name")
    private String cityName;
    @JsonProperty("country_name")
    private String countryName;
    @JsonProperty("map_coordinates")
    private String mapCoordinates;
    @JsonProperty("country_code")
    private String countryCode;

    public Venue() {
    }

    public Venue(Long venueId, String id, String name, int capacity, String cityName, String countryName,
                 String mapCoordinates, String countryCode) {
        this.venueId = venueId;
        this.id=id;
        this.name = name;
        this.capacity = capacity;
        this.cityName = cityName;
        this.countryName = countryName;
        this.mapCoordinates = mapCoordinates;
        this.countryCode = countryCode;
    }

    public Long getVenueId() {
        return venueId;
    }

    public void setVenueId(Long venueId) {
        this.venueId = venueId;
    }

    @JsonProperty("id")
    public String getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("capacity")
    public Integer getCapacity() {
        return capacity;
    }

    @JsonProperty("capacity")
    public void setCapacity(Integer capacity) {
        this.capacity = capacity;
    }

    @JsonProperty("city_name")
    public String getCityName() {
        return cityName;
    }

    @JsonProperty("city_name")
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    @JsonProperty("country_name")
    public String getCountryName() {
        return countryName;
    }

    @JsonProperty("country_name")
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @JsonProperty("map_coordinates")
    public String getMapCoordinates() {
        return mapCoordinates;
    }

    @JsonProperty("map_coordinates")
    public void setMapCoordinates(String mapCoordinates) {
        this.mapCoordinates = mapCoordinates;
    }

    @JsonProperty("country_code")
    public String getCountryCode() {
        return countryCode;
    }

    @JsonProperty("country_code")
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Venue venue = (Venue) o;
        return capacity == venue.capacity && Objects.equals(venueId, venue.venueId) && Objects.equals(id, venue.id) && Objects.equals(name, venue.name) && Objects.equals(cityName, venue.cityName) && Objects.equals(countryName, venue.countryName) && Objects.equals(mapCoordinates, venue.mapCoordinates) && Objects.equals(countryCode, venue.countryCode);
    }

    @Override
    public int hashCode() {
        return Objects.hash(venueId, id, name, capacity, cityName, countryName, mapCoordinates, countryCode);
    }

    @Override
    public String toString() {
        return "Venue{"  
                "venueId="   venueId  
                ", id='"   id   '\''  
                ", name='"   name   '\''  
                ", capacity="   capacity  
                ", cityName='"   cityName   '\''  
                ", countryName='"   countryName   '\''  
                ", mapCoordinates='"   mapCoordinates   '\''  
                ", countryCode='"   countryCode   '\''  
                '}';
    }
}
**Competitor Class:
**
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "id",
        "name",
        "country",
        "country_code",
        "abbreviation",
        "qualifier",
        "gender"
})
@Entity
public class Competitor implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long competitorId;
    @JsonProperty("id")
    private String id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("country")
    private String country;
    @JsonProperty("country_code")
    private String countryCode;
    @JsonProperty("abbreviation")
    private String abbreviation;
    @JsonProperty("qualifier")
    private String qualifier;
    @JsonProperty("gender")
    private String gender;
    public Competitor() {
    }

    public Competitor(Long competitorId, String id, String name, String country, String countryCode, String abbreviation,
                      String qualifier, String gender) {
        this.competitorId = competitorId;
        this.id=id;
        this.name = name;
        this.country = country;
        this.countryCode = countryCode;
        this.abbreviation = abbreviation;
        this.qualifier = qualifier;
        this.gender = gender;
    }

    public Long getCompetitorId() {
        return competitorId;
    }

    public void setCompetitorId(Long id) {
        this.competitorId = id;
    }
    @JsonProperty("id")
    public String getId() {
        return id;
    }
    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }
    @JsonProperty("name")
    public String getName() {
        return name;
    }
    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }
    @JsonProperty("country")
    public String getCountry() {
        return country;
    }
    @JsonProperty("country")
    public void setCountry(String country) {
        this.country = country;
    }
    @JsonProperty("country_code")
    public String getCountryCode() {
        return countryCode;
    }
    @JsonProperty("country_code")
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    @JsonProperty("abbreviation")
    public String getAbbreviation() {
        return abbreviation;
    }
    @JsonProperty("abbreviation")
    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }
    @JsonProperty("qualifier")
    public String getQualifier() {
        return qualifier;
    }
    @JsonProperty("qualifier")
    public void setQualifier(String qualifier) {
        this.qualifier = qualifier;
    }
    @JsonProperty("gender")
    public String getGender() {
        return gender;
    }
    @JsonProperty("gender")
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Competitor that = (Competitor) o;
        return Objects.equals(competitorId, that.competitorId) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(country, that.country) && Objects.equals(countryCode, that.countryCode) && Objects.equals(abbreviation, that.abbreviation) && Objects.equals(qualifier, that.qualifier) && Objects.equals(gender, that.gender);
    }

    @Override
    public int hashCode() {
        return Objects.hash(competitorId, id, name, country, countryCode, abbreviation, qualifier, gender);
    }

    @Override
    public String toString() {
        return "Competitor{"  
                "competitorId="   competitorId  
                ", id='"   id   '\''  
                ", name='"   name   '\''  
                ", country='"   country   '\''  
                ", countryCode='"   countryCode   '\''  
                ", abbreviation='"   abbreviation   '\''  
                ", qualifier='"   qualifier   '\''  
                ", gender='"   gender   '\''  
                '}';
    }
} 

Events Class:

@Entity
@JsonPropertyOrder({
        "sport_event_id",
        "start_date",
        "sport_name",
        "competition_name",
        "competition_id",
        "season_name",
        "competitors",
        "venue",
        "probability_home_team_winner",
        "probability_draw",
        "probability_away_team_winner"
})
public class Events implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    private Long eventsId;
    @JsonProperty("sport_event_id")
    private String sportEventId;
    @JsonProperty("start_date")
    private ZonedDateTime startDate;
    @JsonProperty("sport_name")
    private String sportName;
    @JsonProperty("competition_name")
    private String competitionName;
    @JsonProperty("competition_id")
    private String competitionId;
    @JsonProperty("season_name")
    private String seasonName;
    @OneToMany
    @JsonProperty("competitors")
    private List<Competitor> competitors;
    @ManyToOne
    @JoinColumn
    @JsonProperty("venue")
    private Venue venue;
    @JsonProperty("probability_home_team_winner")
    private double probabilityHomeTeamWinner;
    @JsonProperty("probability_draw")
    private double probabilityDraw;
    @JsonProperty("probability_away_team_winner")
    private double probabilityAwayTeamWinner;
    public Events() {
    }

    public Events(Long eventsId, String sportEventId, ZonedDateTime startDate, String sportName, String competitionName, String competitionId, String seasonName,
                  List<Competitor> competitors, Venue venue, double probabilityHomeTeamWinner, double probabilityDraw, double probabilityAwayTeamWinner) {
        this.sportEventId = sportEventId;
        this.startDate = startDate;
        this.sportName = sportName;
        this.competitionName = competitionName;
        this.competitionId = competitionId;
        this.seasonName = seasonName;
        this.competitors = competitors;
        this.venue = venue;
        this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
        this.probabilityDraw = probabilityDraw;
        this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
    }

    public Long getEventsId() {
        return eventsId;
    }

    public void setEventsId(Long eventsId) {
        this.eventsId = eventsId;
    }
    @JsonProperty("sport_event_id")
    public String getSportEventId() {
        return sportEventId;
    }
    @JsonProperty("sport_event_id")
    public void setSportEventId(String sportEventId) {
        this.sportEventId = sportEventId;
    }
    @JsonProperty("start_date")
    public ZonedDateTime getStartDate() {
        return startDate;
    }
    @JsonProperty("start_date")
    public void setStartDate(ZonedDateTime startDate) {
        this.startDate = startDate;
    }
    @JsonProperty("sport_name")
    public String getSportName() {
        return sportName;
    }
    @JsonProperty("sport_name")
    public void setSportName(String sportName) {
        this.sportName = sportName;
    }
    @JsonProperty("competition_name")
    public String getCompetitionName() {
        return competitionName;
    }
    @JsonProperty("competition_name")
    public void setCompetitionName(String competitionName) {
        this.competitionName = competitionName;
    }
    @JsonProperty("competition_id")
    public String getCompetitionId() {
        return competitionId;
    }
    @JsonProperty("competition_id")
    public void setCompetitionId(String competitionId) {
        this.competitionId = competitionId;
    }
    @JsonProperty("season_name")
    public String getSeasonName() {
        return seasonName;
    }
    @JsonProperty("season_name")
    public void setSeasonName(String seasonName) {
        this.seasonName = seasonName;
    }
    @JsonProperty("competitors")
    public List<Competitor> getCompetitors() {return competitors; }

    @JsonProperty("competitors")
    public void setCompetitors(List<Competitor> competitors) {
    this.competitors = competitors;
}
    @JsonProperty("venue")
    public Venue getVenue() {
        return venue;
    }
    @JsonProperty("venue")
    public void setVenue(Venue venue) {
        this.venue = venue;
    }
    @JsonProperty("probability_home_team_winner")
    public double getProbabilityHomeTeamWinner() {
        return probabilityHomeTeamWinner;
    }
    @JsonProperty("probability_home_team_winner")
    public void setProbabilityHomeTeamWinner(double probabilityHomeTeamWinner) {
        this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
    }
    @JsonProperty("probability_draw")
    public double getProbabilityDraw() {
        return probabilityDraw;
    }
    @JsonProperty("probability_draw")
    public void setProbabilityDraw(double probabilityDraw) {
        this.probabilityDraw = probabilityDraw;
    }
    @JsonProperty("probability_away_team_winner")
    public double getProbabilityAwayTeamWinner() {
        return probabilityAwayTeamWinner;
    }
    @JsonProperty("probability_away_team_winner")
    public void setProbabilityAwayTeamWinner(double probabilityAwayTeamWinner) {
        this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Events events = (Events) o;
        return Double.compare(events.probabilityHomeTeamWinner, probabilityHomeTeamWinner) == 0 && Double.compare(events.probabilityDraw, probabilityDraw) == 0 && Double.compare(events.probabilityAwayTeamWinner, probabilityAwayTeamWinner) == 0 && Objects.equals(eventsId, events.eventsId) && Objects.equals(sportEventId, events.sportEventId) && Objects.equals(startDate, events.startDate) && Objects.equals(sportName, events.sportName) && Objects.equals(competitionName, events.competitionName) && Objects.equals(competitionId, events.competitionId) && Objects.equals(seasonName, events.seasonName) && Objects.equals(competitors, events.competitors) && Objects.equals(venue, events.venue);
    }

    @Override
    public int hashCode() {
        return Objects.hash(eventsId, sportEventId, startDate, sportName, competitionName, competitionId, seasonName, competitors, venue, probabilityHomeTeamWinner, probabilityDraw, probabilityAwayTeamWinner);
    }

    @Override
    public String toString() {
        return "Events{"  
                "eventsId="   eventsId  
                ", sportEventId='"   sportEventId   '\''  
                ", startDate="   startDate  
                ", sportName='"   sportName   '\''  
                ", competitionName='"   competitionName   '\''  
                ", competitionId='"   competitionId   '\''  
                ", seasonName='"   seasonName   '\''  
                //", competitors="   competitors  
                ", venue="   venue  
                ", probabilityHomeTeamWinner="   probabilityHomeTeamWinner  
                ", probabilityDraw="   probabilityDraw  
                ", probabilityAwayTeamWinner="   probabilityAwayTeamWinner  
                '}';
    }
} 

In EventsController, I implemented the getItemFromJSon() method which is supposed to return the contents of a Json.

EventsController Class:

@RestController
public class EventsController {
    private final ObjectMapper objectMapper;
    private final EventsServiceImpl eventsServiceImpl;

    public EventsController(EventsServiceImpl eventsServiceImpl, ObjectMapper objectMapper) {
        this.eventsServiceImpl = eventsServiceImpl;
        this.objectMapper= objectMapper;
    }
    @GetMapping("/json/events")
    public Events getItemFromJson() throws IOException {
     /*   InputStream inputStream = new FileInputStream(new File("src/main/resources/BE_data.json"));
        TypeReference<Events> typeReference = new TypeReference<Events>(){};
        return  objectMapper.readValue(inputStream,typeReference);
      */

        return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Events.class);
    }
}

After running the program and calling endpoint, I get a response in the form of :

{
    "sport_event_id": null,
    "start_date": null,
    "sport_name": null,
    "competition_name": null,
    "competition_id": null,
    "season_name": null,
    "competitors": null,
    "venue": null,
    "probability_home_team_winner": 0.0,
    "probability_draw": 0.0,
    "probability_away_team_winner": 0.0
}

What did I do wrong in my code?

For Json deserialisation I used objectMapper.

CodePudding user response:

Please try these POJO classes. I have used this online tool to autogenerate the POJO Objects

public class Competitor{
    public String id;
    public String name;
    public String country;
    public String country_code;
    public String abbreviation;
    public String qualifier;
    public String gender;
}

public class Event{
    public String sport_event_id;
    public Date start_date;
    public String sport_name;
    public String competition_name;
    public String competition_id;
    public String season_name;
    public ArrayList<Competitor> competitors;
    public Venue venue;
    public double probability_home_team_winner;
    public double probability_draw;
    public double probability_away_team_winner;
}

public class Root{
    @JsonProperty("Events") 
    public ArrayList<Event> events;
}

public class Venue{
    public String id;
    public String name;
    public int capacity;
    public String city_name;
    public String country_name;
    public String map_coordinates;
    public String country_code;
}

Then deserialize it like this

return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Root.class);
  • Related