我现在正在学习GSON库和API。 “ TMDBRating”枚举类:
public enum TMDBRating {
A("Adult"),//from true value
PG("Parental Guideline");//from false value
//Blah...
public static TMDBRating setValue(boolean adult){
if(adult) return A;
else return PG;
}
}
我的MOVIE数据模型类
public class Movie extends Model {
@SerializedName("popularity")
private double popularity;
@SerializedName("vote_count")
private long voteCount;
@SerializedName("video")
private boolean video;
@SerializedName("poster_path")
private String posterPath;
@SerializedName("adult")
private TMDBRating adult;
//...
//WHOLE CONSTRUCTOR, SETTER AND GETTER...
public TMDBRating getAdult(){
return adult;
}
public void setAdult(TMDBRating adult) {
this.adult = adult;
}
public void setAdult(boolean adult) {
this.adult = TMDBRating.setValue(adult);
}
//...
}
从https://stackoverflow.com/a/45854701/1784552检索到的我的JSON MOVIE数据:
{
"popularity": 361.946,
"vote_count": 545,
"video": false,
"poster_path": "/a4BfxRK8dBgbQqbRxPs8kmLd8LG.jpg",
"id": 429203,
"adult": false,
"backdrop_path": "/6X2YjjYcs8XyZRDmJAHNDlls7L4.jpg",
"original_language": "en",
"original_title": "The Old Man & the Gun",
"genre_ids": [
35,
80,
18
],
"title": "The Old Man & the Gun",
"vote_average": 6.3,
"overview": "The true story of Forrest Tucker, from his audacious escape from San Quentin at the age of 70 to an unprecedented string of heists that confounded authorities and enchanted the public. Wrapped up in the pursuit are a detective, who becomes captivated with Forrest’s commitment to his craft, and a woman, who loves him in spite of his chosen profession.",
"release_date": "2018-09-28"
}
这是检索数据时得到的:
java.lang.IllegalStateException: Expected STRING but was BOOLEAN at path $[0].adult
。
如何将布尔值转换为Java枚举?我已经为“成人”创建了setter,将其从“ TMDBRating”(如上)转换为枚举值,但是为什么仍然不起作用?序列化为JSON时可以保留布尔值吗?