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.
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);
I am new to java and spring-boot and I am learning about consuming REST endpoints with RestTemplate. I am trying to counsm the Github jobs api, explicity I am trying the GET /positions/ID.json endpoint
I created the following entity as the type that the response should be bound to
package com.example.demo.entity;
import java.util.Date;
public class GithubJob {
private Long id;
private String type;
private String url;
private Date created_at;
private String company;
private String company_url;
private String location;
private String title;
private String description;
private String how_to_apply;
private String company_log;
public GithubJob() {
}
public GithubJob(
Long id,
String type,
String url,
Date created_at,
String company,
String company_url,
String location,
String title,
String description,
String how_to_apply,
String company_log
) {
this.id = id;
this.type = type;
this.url = url;
this.created_at = created_at;
this.company = company;
this.company_url = company_url;
this.location = location;
this.title = title;
this.description = description;
this.how_to_apply = how_to_apply;
this.company_log = company_log;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCompany_url() {
return company_url;
}
public void setCompany_url(String company_url) {
this.company_url = company_url;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHow_to_apply() {
return how_to_apply;
}
public void setHow_to_apply(String how_to_apply) {
this.how_to_apply = how_to_apply;
}
public String getCompany_log() {
return company_log;
}
public void setCompany_log(String company_log) {
this.company_log = company_log;
}
#Override
public String toString() {
return "GithubJob{" +
"id=" + id +
", type='" + type + '\'' +
", url='" + url + '\'' +
", created_at=" + created_at +
", company='" + company + '\'' +
", company_url='" + company_url + '\'' +
", location='" + location + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", how_to_apply='" + how_to_apply + '\'' +
", company_log='" + company_log + '\'' +
'}';
}
}
This is the method
public GithubJob getGithubJobById(String id) {
RestTemplate restTemplate = new RestTemplate();
GithubJob githubJob = restTemplate.getForObject("https://jobs.github.com/positions/{id}.json", GithubJob.class, id);
return githubJob;
}
I am getting the following error message
Error while extracting response for type [class com.example.demo.entity.GithubJob] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.example.demo.entity.GithubJob` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.example.demo.entity.GithubJob` out of START_ARRAY token at [Source: (PushbackInputStream); line: 1, column: 1]
Finally just to mention that the id exists
UPDATE 1
This es the response I am expecting https://jobs.github.com/positions/1ed5d4dc-d16e-4371-bf8f-8398151b8342.json
UPDATE 2
The original error was related to that I am using Long type for id. Using String solve the initial message. Now I am getting this message
JSON parse error: Cannot deserialize value of type java.util.Date
from String "Wed Jan 20 15:09:48 UTC 2021"
I managed to solve this problem by first making the data type of the id field to String and then adding the pattern with value to "EEE MMM d hh: mm: ss z yyyy", both cases were the reasons why the answer could not be parsed
The final result is the following
package com.example.demo.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class GithubJob {
private String id;
private String type;
private String url;
#JsonFormat(pattern = "EEE MMM d hh:mm:ss z yyyy")
private Date created_at;
private String company;
private String company_url;
private String location;
private String title;
private String description;
private String how_to_apply;
private String company_log;
public GithubJob() {
}
public GithubJob(
String id,
String type,
String url,
Date created_at,
String company,
String company_url,
String location,
String title,
String description,
String how_to_apply,
String company_log
) {
this.id = id;
this.type = type;
this.url = url;
this.created_at = created_at;
this.company = company;
this.company_url = company_url;
this.location = location;
this.title = title;
this.description = description;
this.how_to_apply = how_to_apply;
this.company_log = company_log;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCompany_url() {
return company_url;
}
public void setCompany_url(String company_url) {
this.company_url = company_url;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHow_to_apply() {
return how_to_apply;
}
public void setHow_to_apply(String how_to_apply) {
this.how_to_apply = how_to_apply;
}
public String getCompany_log() {
return company_log;
}
public void setCompany_log(String company_log) {
this.company_log = company_log;
}
#Override
public String toString() {
return "GithubJob{" +
"id=" + id +
", type='" + type + '\'' +
", url='" + url + '\'' +
", created_at=" + created_at +
", company='" + company + '\'' +
", company_url='" + company_url + '\'' +
", location='" + location + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", how_to_apply='" + how_to_apply + '\'' +
", company_log='" + company_log + '\'' +
'}';
}
}
I have multiple Entities mapped to my MySQL database and I can map those entities into relevant objects using Spring's CrudRepository. The three entities are: Snapshot, Market, and Contract
Each Snapshot contains a unique id, a timestamp, and a List of Market objects
Each Market contains a unique primary key id, a nonUniquemarketId, name, url, ...., and List of Contract objects.
Each Contract contains fields regarding pricing information.
The nonUniqueMarketId is an id given by the API I am getting data from. It only occurs once in each Snapshot's List of Market objects
I am wondering if it is possible to get the List of Contracts from a specific Market in List of Markets from a specific Snapshot. That is, if I have a Snapshot's timestamp and a nonUniqueMarketId, is it possible to write a query that looks at all the Snapshots in the DB, gets the one with the given timestamp, then looks at that Snapshot's List of Markets and either gets that Market whose nonUniqueMarketId is given or the List of Contracts field in it?
More generally, I know what Snapshot I want and what Market I want, is it possible to get that specific Market given those two parameters?
Snapshot.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Snapshot{
#Id
private Integer hashId;
#JsonProperty("markets")
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
private List<Market> markets;
private long timestamp;
public Snapshot(List<Market> markets, long timestamp, Integer hashId) {
this.markets = markets;
this.timestamp = timestamp;
this.hashId = hashId;
}
public Snapshot() {
}
public void setMarkets(List<Market> markets){
this.markets = markets;
}
public List<Market> getMarkets(){
return markets;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Integer getHashId() {
return hashId;
}
public void setHashId(Integer hashId) {
this.hashId = hashId;
}
#Override
public String toString() {
return "Snapshot{" +
"hashId=" + hashId +
", markets=" + markets +
", timestamp=" + timestamp +
'}';
}
}
Market.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Market {
#Id
#GeneratedValue
private Integer marketUniqueID;
#JsonProperty("timeStamp")
private String timeStamp;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
#JsonProperty("contracts")
private List<Contract> contracts;
#JsonProperty("url")
private String url;
#JsonProperty("status")
private String status;
public Market(String timeStamp, String image, String name, int id, String shortName, List<Contract> contracts, String url, String status) {
this.timeStamp = timeStamp;
this.image = image;
this.name = name;
this.id = id;
this.shortName = shortName;
this.contracts = contracts;
this.url = url;
this.status = status;
}
public Market() {
}
public Integer getMarketUniqueID() {
return marketUniqueID;
}
public void setMarketUniqueID(Integer marketUniqueID) {
this.marketUniqueID = marketUniqueID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public List<Contract> getContracts() {
return contracts;
}
public void setContracts(List<Contract> contracts) {
this.contracts = contracts;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "\n\nMarket{" +
"marketUniqueID='" + marketUniqueID + '\'' +
", timeStamp='" + timeStamp + '\'' +
", image='" + image + '\'' +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", contracts=" + contracts +
", url='" + url + '\'' +
", status='" + status + '\'' +
"\n}";
}
}
Contract.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
#Entity
public class Contract {
/*
Why do we need contractUniqueID?:
See explanation in Market.java
Basically, the JsonProperty 'id' field cannot be used as a primary key in the database. We need to create one, so we generate it here.
*/
#Id
#GeneratedValue
private Integer contractUniqueID;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("lastClosePrice")
private double lastClosePrice;
#JsonProperty("bestBuyNoCost")
private double bestBuyNoCost;
#JsonProperty("bestSellNoCost")
private double bestSellNoCost;
#Transient
#JsonProperty("displayOrder")
private int displayOrder; //not sure what this even is supposed to do lol
#JsonProperty("dateEnd")
private String dateEnd;
#JsonProperty("bestSellYesCost")
private double bestSellYesCost;
#JsonProperty("bestBuyYesCost")
private double bestBuyYesCost;
#JsonProperty("lastTradePrice")
private double lastTradePrice;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#JsonProperty("status")
private String status;
public Contract(String image, double lastClosePrice, double bestBuyNoCost, double bestSellNoCost, int displayOrder, String dateEnd, double bestSellYesCost, double bestBuyYesCost, double lastTradePrice, String name, int id, String shortName, String status) {
this.image = image;
this.lastClosePrice = lastClosePrice;
this.bestBuyNoCost = bestBuyNoCost;
this.bestSellNoCost = bestSellNoCost;
this.displayOrder = displayOrder;
this.dateEnd = dateEnd;
this.bestSellYesCost = bestSellYesCost;
this.bestBuyYesCost = bestBuyYesCost;
this.lastTradePrice = lastTradePrice;
this.name = name;
this.id = id;
this.shortName = shortName;
this.status = status;
}
public Contract() {
}
public Integer getContractUniqueID() {
return contractUniqueID;
}
public void setContractUniqueID(Integer contractUniqueID) {
this.contractUniqueID = contractUniqueID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getLastClosePrice() {
return lastClosePrice;
}
public void setLastClosePrice(double lastClosePrice) {
this.lastClosePrice = lastClosePrice;
}
public double getBestBuyNoCost() {
return bestBuyNoCost;
}
public void setBestBuyNoCost(double bestBuyNoCost) {
this.bestBuyNoCost = bestBuyNoCost;
}
public double getBestSellNoCost() {
return bestSellNoCost;
}
public void setBestSellNoCost(double bestSellNoCost) {
this.bestSellNoCost = bestSellNoCost;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public String getDateEnd() {
return dateEnd;
}
public void setDateEnd(String dateEnd) {
this.dateEnd = dateEnd;
}
public double getBestSellYesCost() {
return bestSellYesCost;
}
public void setBestSellYesCost(double bestSellYesCost) {
this.bestSellYesCost = bestSellYesCost;
}
public double getBestBuyYesCost() {
return bestBuyYesCost;
}
public void setBestBuyYesCost(double bestBuyYesCost) {
this.bestBuyYesCost = bestBuyYesCost;
}
public double getLastTradePrice() {
return lastTradePrice;
}
public void setLastTradePrice(double lastTradePrice) {
this.lastTradePrice = lastTradePrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Contract{" +
"contractUniqueID='" + contractUniqueID + '\'' +
", image='" + image + '\'' +
", lastClosePrice=" + lastClosePrice +
", bestBuyNoCost=" + bestBuyNoCost +
", bestSellNoCost=" + bestSellNoCost +
", displayOrder=" + displayOrder +
", dateEnd='" + dateEnd + '\'' +
", bestSellYesCost=" + bestSellYesCost +
", bestBuyYesCost=" + bestBuyYesCost +
", lastTradePrice=" + lastTradePrice +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", status='" + status + '\'' +
'}';
}
}
I'm trying to parse strig xml using JaxB API.
Below is my code
XML
http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
Pojo Classes
#XmlRootElement(name = "employees")
public class FileWrapper {
private LinkedHashSet<Employee> employees;
public LinkedHashSet<Employee> getEmployees() {
return employees;
}
#XmlElement(name = "employee")
public void setEmployees(LinkedHashSet<Employee> employees) {
this.employees = employees;
}
}
Employee.java
import javax.xml.bind.annotation.XmlAttribute;
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlAttribute
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlAttribute
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlAttribute
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlAttribute
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlAttribute
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlAttribute
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlAttribute
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
MainEntry
public class TestEntryPoint {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("XML from above link as String");
FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);
List<Employee> emp = new ArrayList<Employee>(person.getEmployees());
System.out.println(emp.get(0).getFirstname());
}
}
So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.
What am doing wrong ? Canyone suggest please ?
Thanks
Annotations in Employee class refer to XML attributes instead of the elements.
Here is corrected version:
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlElement(name = "division")
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlElement(name = "firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlElement(name = "title")
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlElement(name = "building")
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlElement(name = "room")
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlElement(name = "supervisor")
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlElement(name = "lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}