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 was trying to show Json output in my Android app. I'm dropping the site link here: https://jsonplaceholder.typicode.com/users
When i try to show ResponseDTO.java output in AddressPage, it works. But when change it to Address.java or AddressDTO.java, i get null value in my app(in AddressPage)
AddressPage.java:
public class AdressPage extends AppCompatActivity {
String id, usr_name;
List<Address> userAdressList;
TextView street, suite, city, zipcode, latText, lngText;
List<GeoDTO> geoDTOList;
Float lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address_page_adapter);
defVars();
get_parameters();
request();
}
public void get_parameters() {
Bundle bundle = getIntent().getExtras();
id = bundle.getString("post_id");
usr_name = bundle.getString("user_name");
}
public void defVars() {
street = findViewById(R.id.street);
suite = findViewById(R.id.suite);
city = findViewById(R.id.city);
zipcode = findViewById(R.id.zipcode);
latText = findViewById(R.id.lat);
lngText = findViewById(R.id.lng);
}
public void assignment(List<Address> addresses) {
street.setText(""+addresses.get(0).getStreet());
suite.setText(""+addresses.get(0).getSuite());
city.setText(""+addresses.get(0).getCity());
zipcode.setText(""+addresses.get(0).getZipcode());
/*zipcode.setText(id);
street.setText(id);
suite.setText(usr_name);
city.setText(usr_name);*/
}
public void request() {
userAdressList = new ArrayList<>();
Call<List<Address>> call = ManagerAll.getInstance().managerGetAdress(id, usr_name);
call.enqueue(new Callback<List<Address>>() {
#Override
public void onResponse(Call<List<Address>> call, Response<List<Address>> response) {
if (response.isSuccessful()) {
userAdressList = response.body();
assignment(userAdressList);
}
}
#Override
public void onFailure(Call<List<Address>> call, Throwable t) {
}
});
}
}
AddressDTO or Address (Same codes):
public class Address implements Serializable {
private String zipcode;
private Geo geo;
private String suite;
private String city;
private String street;
public void setZipcode(String zipcode){
this.zipcode = zipcode;
}
public String getZipcode(){
return zipcode;
}
public void setGeo(Geo geo){
this.geo = geo;
}
public Geo getGeo(){
return geo;
}
public void setSuite(String suite){
this.suite = suite;
}
public String getSuite(){
return suite;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public void setStreet(String street){
this.street = street;
}
public String getStreet(){
return street;
}
#Override
public String toString(){
return
"Address{" +
"zipcode = '" + zipcode + '\'' +
",geo = '" + geo + '\'' +
",suite = '" + suite + '\'' +
",city = '" + city + '\'' +
",street = '" + street + '\'' +
"}";
}
}
RestApi interface:
public interface RestApi {
#GET("/users")
Call<List<ResponseDTO>> bring();
#GET("/users") Call<List<ResponseDTO>> bringResponse(#Query("id")String id, #Query("username")String usr_name);
#GET("/users") Call<List<Address>> bringAdress(#Query("id")String id, #Query("username")String usr_name);
//#GET("/users") Call<List<GeoDTO>> bringGeo(#Query("id")String id, #Query("username")String usr_name);
}
ManagerAll.java:
public class ManagerAll extends BaseManager {
private static ManagerAll ourInstance = new ManagerAll();
public static synchronized ManagerAll getInstance() {
return ourInstance;
}
public Call<List<ResponseDTO>> bringCall() {
Call<List<ResponseDTO>> x = getRestApi().bring();
return x;
}
public Call<List<Address>> managerGetAdress(String post, String username) {
Call<List<Address>> y = getRestApi().bringAdress(post, username);
return y;
}
public Call<List<ResponseDTO>> managerBringResponse(String post, String username) {
Call<List<ResponseDTO>> z = getRestApi().bringResponse(post, username);
return z;
}
}
This is ResponseDTO:
public class ResponseDTO implements Serializable {
private String website;
private AddressDTO address;
private String phone;
private String name;
private CompanyDTO company;
private int id;
private String email;
private String username;
public void setWebsite(String website){
this.website = website;
}
public String getWebsite(){
return website;
}
public void setAddress(AddressDTO address){
this.address = address;
}
public AddressDTO getAddress(){
return address;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setCompany(CompanyDTO company){
this.company = company;
}
public CompanyDTO getCompany(){
return company;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
#Override
public String toString(){
return
"ResponseDTO{" +
"website = '" + website + '\'' +
",address = '" + address + '\'' +
",phone = '" + phone + '\'' +
",name = '" + name + '\'' +
",company = '" + company + '\'' +
",id = '" + id + '\'' +
",email = '" + email + '\'' +
",username = '" + username + '\'' +
"}";
}
}
As i said, when i set the list in AddressPage AddressDto(or Address) to Response i can get datas. But it gives me null value when i set it to AddressDto.
GeoDTO:
public class GeoDTO implements Serializable {
private String lng;
private String lat;
public void setLng(String lng){
this.lng = lng;
}
public String getLng(){
return lng;
}
public void setLat(String lat){
this.lat = lat;
}
public String getLat(){
return lat;
}
#Override
public String toString(){
return
"GeoDTO{" +
"lng = '" + lng + '\'' +
",lat = '" + lat + '\'' +
"}";
}
}
CompanyDTO:
public class CompanyDTO implements Serializable {
private String bs;
private String catchPhrase;
private String name;
public void setBs(String bs){
this.bs = bs;
}
public String getBs(){
return bs;
}
public void setCatchPhrase(String catchPhrase){
this.catchPhrase = catchPhrase;
}
public String getCatchPhrase(){
return catchPhrase;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
#Override
public String toString(){
return
"CompanyDTO{" +
"bs = '" + bs + '\'' +
",catchPhrase = '" + catchPhrase + '\'' +
",name = '" + name + '\'' +
"}";
}
}
Address class is not similar to your json response so you are not getting data from your service . You can read first ResponseDTO data then read address data from json.
I am new to JPA and I am trying to persist an Entity that will run through 3 stages New, Processing and Completed. I want the below timestamps to be updated accordingly
#Entity
#Table(name = "feedertable")
#JsonIgnoreProperties(value = { "processStatus" })
public class FeederTable {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private String id;
private String orderID;
private String status;
#Column(name="CREATEDDATETIME",nullable = false)
private Timestamp createdDateTime;
#Column(name="PROCESSSTATUS",nullable = false)
private String processStatus;
#Column(name="HOSTNAME",nullable = true)
private String hostName;
//#Temporal(TemporalType.TIMESTAMP)
#Column(name="PROCESSINGDATETIME",nullable = false)
private Timestamp processingDateTime;
#Column(name="COMPLETEDDATETIME",nullable = false)
private Timestamp completedDateTime; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Timestamp getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Timestamp createdDateTime) {
this.createdDateTime = createdDateTime;
}
public String getProcessStatus() {
return processStatus;
}
public void setProcessStatus(String processStatus) {
this.processStatus = processStatus;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Timestamp getProcessingDateTime() {
return processingDateTime;
}
public void setProcessingDateTime(Timestamp processingDateTime) {
this.processingDateTime = processingDateTime;
}
public Timestamp getCompletedDateTime() {
return completedDateTime;
}
public void setCompletedDateTime(Timestamp completedDateTime) {
this.completedDateTime = completedDateTime;
}
#Override
public String toString() {
return "FeederTable{" +
"id='" + id + '\'' +
", orderID='" + orderID + '\'' +
", status='" + status + '\'' +
", createdDateTime=" + createdDateTime +
", processStatus='" + processStatus + '\'' +
", hostName='" + hostName + '\'' +
", processingDateTime=" + processingDateTime +
", completedDateTime=" + completedDateTime +
'}';
}
Persist in JPARepository:
FeederTable feederTable = new FeederTable();
feederTable.setOrderID(orderId);
feederTable.setStatus(status);
feederTable.setCreatedDateTime(new Timestamp(format.getTime())); feederTable.setProcessStatus("New");
feederTable.setHostName(hostname);
feederTable.setCompletedDateTime(null);
feederTable.setProcessingDateTime(null);
repository.save(feederTable);
However when first time the Entity is persisted, All the Timestamps are populated. I want the PROCESSINGDATETIME and COMPLETEDDATETIME as null and populate it only when it reaches corresponding status. Any idea how to acheive it?.
I did a similar thing in my project using #PrePersist and #PreUpdate annotations.
There are other lifecycle hooks that you can use. Read about them here.
MyEntity{
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Temporal(TemporalType.TIMESTAMP)
private Date updationDate;
#PrePersist
public void onCreate() {
creationDate = new Date();
}
#PreUpdate
public void onUpdate() {
updationDate = new Date();
}
}
Did I understand your question correctly? Is this what you were looking for?
Using Hibernate 3.6.0
I'm having a real hard time understanding hibernate. I keep running into this issue with lazy initialization exception.
I have an Event entity with a one-to-many relationship with RSVP. When a run a test get back a list of events it works. But when I'm making the call in my controller in order to return it as json, I run into this lazy init error.
This is my event class
#Entity
#Table(name = "EVENT")
public class Event implements Serializable {
#SequenceGenerator(name="event", sequenceName="EVENT_PK_SEQ")
#GeneratedValue(generator="event",strategy=GenerationType.SEQUENCE)
#Id
#Column(name = "EVENT_ID")
private int id;
#Column(name = "DATE_TIME")
private Date date;
#Column(name = "EVENT_NAME")
private String name;
#Column(name = "EVENT_PARTICIPANT_LIMIT")
private int limit;
#Column(name = "EVENT_VISIBILITY")
private boolean visibilty;
#Column(name = "EVENT_LOCATION")
private String location;
#Column(name = "EVENT_DESCRIPTION")
private String description;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private User author;
private Date create_date;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventType eventType;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventClass eventClass;
#OneToMany(cascade = CascadeType.ALL)
private Set<RSVP> rsvps = new HashSet<RSVP>();
#ManyToMany(mappedBy="event")
private Set<Group> groups = new HashSet<Group>();
public Event(int id, Date date, String name, int limit, boolean visibilty, String location, String description,
User author, Date create_date, EventType eventType, EventClass eventClass) {
super();
this.id = id;
this.date = date;
this.name = name;
this.limit = limit;
this.visibilty = visibilty;
this.location = location;
this.description = description;
this.author = author;
this.create_date = create_date;
this.eventType = eventType;
this.eventClass = eventClass;
}
public Event(){
super();
}
#Override
public String toString() {
return "Event [id=" + id + ", date=" + date + ", name=" + name + ", limit=" + limit + ", visibilty=" + visibilty
+ ", location=" + location + ", description=" + description + ", author=" + author + ", create_date="
+ create_date + ", eventType=" + eventType + ", eventClass=" + eventClass + ", rsvps=" + rsvps
+ ", groups=" + groups + "]";
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isVisibilty() {
return visibilty;
}
public void setVisibilty(boolean visibilty) {
this.visibilty = visibilty;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
public EventClass getEventClass() {
return eventClass;
}
public void setEventClass(EventClass eventClass) {
this.eventClass = eventClass;
}
public Set<RSVP> getRsvps() {
return rsvps;
}
public void setRsvps(Set<RSVP> rsvps) {
this.rsvps = rsvps;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
My RSVP
#Entity
#Table(name="RSVP")
public class RSVP {
#Id
#Column(name="RSVP_ID")
#SequenceGenerator(name="rsvp", sequenceName="RSVP_PK_SEQ")
#GeneratedValue(generator="rsvp",strategy=GenerationType.SEQUENCE)
private int rsvpId;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
#JoinColumn(name="STATUS_ID")
private RSVPStatus status;
#ManyToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="EVENT_ID")
private Event event;
public RSVP(int rsvpId, RSVPStatus status, User user, Event event) {
super();
this.rsvpId = rsvpId;
this.status = status;
this.user = user;
this.event = event;
}
public RSVP() {
}
#Override
public String toString() {
return "RSVP [rsvpId=" + rsvpId + ", status=" + status + ", user=" + user + ", event=" + event + "]";
}
public int getRsvpId() {
return rsvpId;
}
public void setRsvpId(int rsvpId) {
this.rsvpId = rsvpId;
}
public RSVPStatus getStatus() {
return status;
}
public void setStatus(RSVPStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
MY controller
public class MyController {
private static SessionFactory sf = HibernateUtils.getSessionFactory();
private DataFacade df = new DataFacade(sf);
#RequestMapping(value="home", method=RequestMethod.GET,
consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<List<Event>> getUserCal(){
DataFacade df = new DataFacade(sf);
List<Event> events= df.getAllEventsByAuthor(1);
for(Event e:events){
System.out.println(e);
}
return new ResponseEntity<List<Event>>(events,HttpStatus.OK);
}
}
Your RSVP collection is fetched lazily. (If you don't specify a fetch type, the default is lazy). You need to change it to eager if you are planning to access it after the Hibernate session is closed:
#OneToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Set<RSVP> rsvps = new HashSet<RSVP>();