简体   繁体   中英

Java how to set data in model

I have a model below call "TitleModels" which i use to add my data I get from my Api. Unfortunately i am unable to set the data in RatingModels. What is the best way to set data to a model using an array? Unfortunately i get the error "incompatible types: Rating cannot be converted to RatingModels".

The code I am done so far:

             import com.alienvers.alienversapp.models.TitleModels;


             private List<TitleModels> inTheaterListMovie = new ArrayList<>();

             //In theater movies data
             for (int i = 0; i < response.body().getInTheaterMovies().size(); i++){
                 InTheaterMovies movie = response.body().getInTheaterMovies().get(i);
                 TitleModels models = new TitleModels();
                 models.setPosterUrl(movie.getPosterUrl());
                 models.setTitle(movie.getTitle());
                 models.setTypeName("movies");
                 models.setReleaseDate(movie.getRelease());
                 models.setPlot(movie.getVideoQuality());
                 models.setId(movie.getVideosId());

                 models.setRatingModels(movie.getRating());



                 inTheaterListMovie.add(models);

             }

The error I get:

error: incompatible types: Rating cannot be converted to RatingModels models.setRatingModels(movie.getRating());

Model:

public class TitleModels {

   public String videosId;
   public String title;
   public String description;
   public String slug;
   public Boolean isPaid;
   public String release;
   public String runtime;
   public String videoQuality;
   public String thumbnailUrl;
   public String posterUrl;
   public RatingModels rating;

   public String getVideosId() {
       return videosId;
   }

   public void setVideosId(String videosId) {
       this.videosId = videosId;
   }

   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 getSlug() {
      return slug;
   }

   public void setSlug(String slug) {
      this.slug = slug;
   }

   public Boolean getIsPaid() {
      return isPaid;
   }

   public void setIsPaid(Boolean isPaid) {
      this.isPaid = isPaid;
   }

   public String getRelease() {
      return release;
   }

   public void setRelease(String release) {
      this.release = release;
   }

   public String getRuntime() {
      return runtime;
   }

   public void setRuntime(String runtime) {
      this.runtime = runtime;
   }

   public String getVideoQuality() {
      return videoQuality;
   }

   public void setVideoQuality(String videoQuality) {
      this.videoQuality = videoQuality;
   }

   public String getThumbnailUrl() {
      return thumbnailUrl;
   }

   public void setThumbnailUrl(String thumbnailUrl) {
      this.thumbnailUrl = thumbnailUrl;
   }

   public String getPosterUrl() {
      return posterUrl;
   }

   public void setPosterUrl(String posterUrl) {
      this.posterUrl = posterUrl;
   }

   public RatingModels getRating() {
      return rating;
   }

   public void setRating(RatingModels rating) {
      this.rating = rating;
   }

}

Here my Rating Model:

public class RatingModels {

   public String userRating;
   public String userRatingIcon;
   public String titleRatingCount;
   public String titleRatingScore;

   public String getUserRating() {
      return userRating;
   }

   public void setUserRating(String userRating) {
      this.userRating = userRating;
   }

   public String getUserRatingIcon() {
      return userRatingIcon;
   }

   public void setUserRatingIcon(String userRatingIcon) {
      this.userRatingIcon = userRatingIcon;
   }

   public String getTitleRatingCount() {
      return titleRatingCount;
   }

   public void setTitleRatingCount(String titleRatingCount) {
      this.titleRatingCount = titleRatingCount;
   }

   public String getTitleRatingScore() {
      return titleRatingScore;
   }

   public void setTitleRatingScore(String titleRatingScore) {
      this.titleRatingScore = titleRatingScore;
   }

}

Response i get from the server in json format:

  "in_theater_movies": [
    {
      "videos_id": "16",
      "title": "Midway",
      "description": "Après la débâcle de Pearl Harbor qui a laissé la flotte américaine dévastée, la marine impériale japonaise prépare une nouvelle attaque qui devrait éliminer définitivement les forces aéronavales restantes de son adversaire.  La campagne du Pacifique va se jouer dans un petit atoll isolé du Pacifique nord : Midway.",
      "slug": "16-midway",
      "is_paid": true,
      "release": "2019",
      "runtime": "138",
      "video_quality": "HD",
      "thumbnail_url": "http://localhost/assets/images/upload/backdrops/1ZSjrBUHP2jm1QlQEyLGufL289q_thumb.jpg",
      "poster_url": "http://localhost/assets/images/upload/posters/pcd4hAysR1RJXlrxplvT5Ag2U1H_thumb.jpg",
      "rating": {
        "user_rating": null,
        "user_rating_icon": null,
        "title_rating_count": "0",
        "title_rating_score": null
      }
    },
    {
      "videos_id": "190",
      "title": "Maléfique : Le Pouvoir du Mal",
      "description": "Plusieurs années après avoir découvert pourquoi la plus célèbre méchante Disney avait un cœur si dur et ce qui l’avait conduit à jeter un terrible sort à la princesse Aurore, Maléfique, le pouvoir du mal, continue d’explorer les relations complexes entre la sorcière et la future reine, alors qu’elles nouent d’autres alliances et affrontent de nouveaux adversaires dans leur combat pour protéger leurs terres et les créatures magiques qui les peuplent.",
      "slug": "190-malefique-le-pouvoir-du-mal",
      "is_paid": true,
      "release": "2019",
      "runtime": "110",
      "video_quality": "HD",
      "thumbnail_url": "http://localhost/assets/images/upload/backdrops/skvI4rYFrKXS73BJxWGH54Omlvv_thumb.jpg",
      "poster_url": "http://localhost/assets/images/upload/posters/eDVBn53859HvDyzVleU4fIvPvcO_thumb.jpg",
      "rating": {
        "user_rating": null,
        "user_rating_icon": null,
        "title_rating_count": "2",
        "title_rating_score": "60.0000"
      }
    },
    {
      "videos_id": "191",
      "title": "Angry Birds : Copains comme cochons",
      "description": "Les oiseaux et les cochons continuent de se battre sans relâche. Mais la menace d’un nouvel adversaire vient perturber les voisins ennemis. Red, Chuck, Bombe et l’Aigle Vaillant recrutent Silver, la sœur de Chuck et s’associent aux cochons Léonard, son assistante Courtney et Garry (le geek), pour former une équipe improbable et tenter de sauver leurs foyers !",
      "slug": "191-angry-birds-copains-comme-cochons",
      "is_paid": true,
      "release": "2019",
      "runtime": "96",
      "video_quality": "HD",
      "thumbnail_url": "http://localhost/assets/images/upload/backdrops/k7sE3loFwuU2mqf7FbZBeE3rjBa_thumb.jpg",
      "poster_url": "http://localhost/assets/images/upload/posters/xNSejOLGZPUjWmBEluklJYoqqOc_thumb.jpg",
      "rating": {
        "user_rating": null,
        "user_rating_icon": null,
        "title_rating_count": "1",
        "title_rating_score": "10.0000"
      }
    },
    {
      "videos_id": "192",
      "title": "Queens",
      "description": "Des stripteaseuses se lient d’amitié et décident de conjuguer leurs talents pour arnaquer et prendre leur revanche sur leurs riches clients de Wall Street.\r\n Leur plan fonctionne à merveille, mais argent et vie facile les poussent à prendre de plus en plus de risques…",
      "slug": "192-queens",
      "is_paid": true,
      "release": "2019",
      "runtime": "107",
      "video_quality": "HD",
      "thumbnail_url": "http://localhost/assets/images/upload/backdrops/5GynP6w2OQWSbKnCLHrBIriF4Cw_thumb.jpg",
      "poster_url": "http://localhost/assets/images/upload/posters/zDkguic7WqrTeLmFGOVQ9OQfdI5_thumb.jpg",
      "rating": {
        "user_rating": null,
        "user_rating_icon": null,
        "title_rating_count": "1",
        "title_rating_score": "50.0000"
      }
    },
  ],

You have different types

models.setRatingModels(movie.getRating());

According to TitleModels definition:

public void setRating(RatingModels rating) {
      this.rating = rating;
}

However InTheaterMovies movie method movie.getRating() return Rating and not RatingModels . Even if both InTheaterMovies and TitleModels has field with the same name, type of the filed is different.

RatingModels rating; 

vs

Rating rating; 

I guess you need to update your jsonParser , to make sure that InTheaterMovies raiting field has type of RatingModels .

Or just create a new RatingModels from Rating object. Something like this:

models.setRatingModels(RatingModels.fromRating(movie.getRating()));

where RatingModels.fromRating is a static factory method:

RatingModels Ratring fromRatring(Ratring rating) { 
  RatingModels model = new RatingModels(); 
  model.setUserRating(ratring.getUserRating()); 
  ... // set all reaming properties
  return model;
}

I hope this helps.

You are trying to set Rating object to RatingModels inside the method TitleModels using the set method setRatingModels which is not possible.

You have to unpack the movie.getRating() and set the attributes to RatingModels and then set the object using:

models.setRatingModels(movie.getRating());

You can do something like:

RatingModels model = new Rating Model();
model.setsetUserRating(movie.getRating().get(i).getUserRating());
.
.
.

Then

models.setRatingModels(model);

You can easily do this using the package 'Gson'. If you are using Android-studio add the respective gradle

Gson gradle

compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'

Then create a new model

public class TheaterMovies {

@SerializedName("in_theater_movies")
private List<TitleModels> titles;


public List<TitleModels> getTitles() {
    return titles;
}

public void setTitles(List<TitleModels> titles) {
    this.titles = titles;
}}

I suppose that the response in Json format that you posted is available from response.getBody()

Then do this,

Gson gson = new Gson();
TheaterMovies movies = gson.fromJson(response.getBody(), TheaterMovies.class);

Tried using the response from your question and is working perfectly. Hope it helps. Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM