Parse Json with Gson in EnumClass - java

I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks

Related

How to set Json string array to Java object using Java

I have following JSON string that I need to set to the Java objects of POJO class.
What method should I follow?
{"status":"FOUND","messages":null,"sharedLists": [{"listId":"391647d","listName":"/???","numberOfItems":0,"colla borative":false,"displaySettings":true}] }
I tried using Gson but it did not work for me.
Gson gson = new Gson();
SharedLists target = gson.fromJson(sb.toString(), SharedLists.class);
Following is my SharedLists pojo
public class SharedLists {
#SerializedName("listId")
private String listId;
#SerializedName("listName")
private String listName;
#SerializedName("numberOfItems")
private int numberOfItems;
#SerializedName("collaborative")
private boolean collaborative;
#SerializedName("displaySettings")
private boolean displaySettings;
public int getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(int numberOfItems) {
this.numberOfItems = numberOfItems;
}
public boolean isCollaborative() {
return collaborative;
}
public void setCollaborative(boolean collaborative) {
this.collaborative = collaborative;
}
public boolean isDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(boolean displaySettings) {
this.displaySettings = displaySettings;
}
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
}
Following is your JSON string.
{
"status": "FOUND",
"messages": null,
"sharedLists": [
{
"listId": "391647d",
"listName": "/???",
"numberOfItems": 0,
"colla borative": false,
"displaySettings": true
}
]
}
Clearly sharedLists is a JSON array within the outer JSON object.
So I have two classes as follows (created from http://www.jsonschema2pojo.org/ by providing your JSON as input)
ResponseObject - Represents the outer object
public class ResponseObject {
#SerializedName("status")
#Expose
private String status;
#SerializedName("messages")
#Expose
private Object messages;
#SerializedName("sharedLists")
#Expose
private List<SharedList> sharedLists = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getMessages() {
return messages;
}
public void setMessages(Object messages) {
this.messages = messages;
}
public List<SharedList> getSharedLists() {
return sharedLists;
}
public void setSharedLists(List<SharedList> sharedLists) {
this.sharedLists = sharedLists;
}
}
and the SharedList - Represents each object within the array
public class SharedList {
#SerializedName("listId")
#Expose
private String listId;
#SerializedName("listName")
#Expose
private String listName;
#SerializedName("numberOfItems")
#Expose
private Integer numberOfItems;
#SerializedName("colla borative")
#Expose
private Boolean collaBorative;
#SerializedName("displaySettings")
#Expose
private Boolean displaySettings;
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public Integer getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(Integer numberOfItems) {
this.numberOfItems = numberOfItems;
}
public Boolean getCollaBorative() {
return collaBorative;
}
public void setCollaBorative(Boolean collaBorative) {
this.collaBorative = collaBorative;
}
public Boolean getDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(Boolean displaySettings) {
this.displaySettings = displaySettings;
}
}
Now you can parse the entire JSON string with GSON as follows
Gson gson = new Gson();
ResponseObject target = gson.fromJson(inputString, ResponseObject.class);
Hope this helps.

Populate a tableview in javafx

I have a tableview in javafx which i want to populate with objects type Course. The idea is that in my Course class, I hava a composite primary key which is a diifferent class CourseId. I want to add in one column of the tableview the courseno which is present in CourseId class, but i dont know how to get it.
My course class:
package com.licenta.ascourses.ui.model;
import java.io.Serializable;
public class Course implements Serializable {
private CourseId idCourse = new CourseId();
private int year;
private int semester;
private String discipline;
private String professor;
public Course() {
}
public Course(CourseId idCourse, int year, int semester) {
super();
this.idCourse = idCourse;
this.year = year;
this.semester = semester;
}
public Course(CourseId idCourse, int year, int semester, String discipline, String professor) {
this.idCourse=idCourse;
this.year = year;
this.semester = semester;
this.discipline = discipline;
this.professor = professor;
}
public CourseId getIdCourse() {
return idCourse;
}
public void setIdCourse(CourseId idCourse) {
this.idCourse = idCourse;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
public String getDiscipline() {
return discipline;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public String getProfessor() {
return professor;
}
public void setProfessor(String professor) {
this.professor = professor;
}
}
My courseId class:
package com.licenta.ascourses.ui.model;
import java.io.Serializable;
public class CourseId implements Serializable {
private int idDiscipline;
private int idProfessor;
private int courseNo;
public CourseId() {
}
public CourseId(int idDiscipline, int idProfessor, int courseNo) {
super();
this.idDiscipline = idDiscipline;
this.idProfessor = idProfessor;
this.courseNo = courseNo;
}
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public int getIdProfessor() {
return idProfessor;
}
public void setIdProfessor(int idProfessor) {
this.idProfessor = idProfessor;
}
public int getCourseNo() {
return courseNo;
}
public void setCourseNo(int courseNo) {
this.courseNo = courseNo;
}
public boolean equals(Object o) {
return true;
}
public int hashCode() {
return 1;
}
}
columnNumarCurs.setCellValueFactory(new PropertyValueFactory<Course, Integer>(""));
columnAn.setCellValueFactory(new PropertyValueFactory<Course, Integer>("year"));
columnSemestru.setCellValueFactory(new PropertyValueFactory<Course, Integer>("semester"));
columnDisciplina.setCellValueFactory(new PropertyValueFactory<Course, String>("discipline"));
columnProfesor.setCellValueFactory(new PropertyValueFactory<Course, String>("professor"));
The setCellValueFactory method requires a Callback<CellDataFeatures, ObservableValue>: i.e. a function that maps a CellDataFeatures object to an ObservableValue containing the value to be displayed. Since the value you have is an int, and assuming columnNumarCurs is a TableColumn<Course, Number>, the appropriate ObservableValue type is an IntegerProperty. So you can do:
columnNumarCurs.setCellValueFactory(
cellData -> new SimpleIntegerProperty(cellData.getValue().getIdCourse().getCourseNo()));

List of class objects from list of strings

I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);

null values returning from gson.fromJson

I have some values in my object are returning by value null when converting from json to object and some others doesn't,i can't figure out why is that happening
here's my code to convert
OriginalMovie originalMovie = gson.fromJson(jsonString, OriginalMovie.class);
here's my json
{"page":1,
"results":[{"adult":false,
"backdrop_path":"/o4I5sHdjzs29hBWzHtS2MKD3JsM.jpg",
"genre_ids":[878,28,53,12],
"id":87101,"original_language":"en",
"original_title":"Terminator Genisys",
"overview":"The year is 2029. John Connor, leader of the resistance continues the war against the machines.",
"release_date":"2015-07-01",
"poster_path":"/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg",
"popularity":54.970301,
"title":"Terminator Genisys","video":false,
"vote_average":6.4,
"vote_count":197}],
"total_pages":11666,"total_results":233312}
and here's my base class (contains results)
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class OriginalMovie
{
private long page;
private List<Result> results = new ArrayList<Result>();
private long totalPages;
private long totalResults;
public long getPage()
{
return page;
}
public void setPage(long page)
{
this.page = page;
}
public List<Result> getResults()
{
return results;
}
public void setResults(List<Result> results)
{
this.results = results;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages)
{
this.totalPages = totalPages;
}
public long getTotalResults()
{
return totalResults;
}
public void setTotalResults(long totalResults)
{
this.totalResults = totalResults;
}
}
and here's my other class
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class Result {
private boolean adult;
private String backdropPath;
private List<Long> genreIds = new ArrayList<Long>();
private long id;
private String originalLanguage;
private String originalTitle;
private String overview;
private String releaseDate;
private String posterPath;
private double popularity;
private String title;
private boolean video;
private double voteAverage;
private long voteCount;
public boolean isAdult()
{
return adult;
}
public void setAdult(boolean adult)
{
this.adult = adult;
}
public String getBackdropPath()
{
return backdropPath;
}
public void setBackdropPath(String backdropPath)
{
this.backdropPath = backdropPath;
}
public List<Long> getGenreIds()
{
return genreIds;
}
public void setGenreIds(List<Long> genreIds)
{
this.genreIds = genreIds;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getOriginalLanguage()
{
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage)
{
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle()
{
return originalTitle;
}
public void setOriginalTitle(String originalTitle)
{
this.originalTitle = originalTitle;
}
public String getOverview()
{
return overview;
}
public void setOverview(String overview)
{
this.overview = overview;
}
public String getReleaseDate()
{
return releaseDate;
}
public void setReleaseDate(String releaseDate)
{
this.releaseDate = releaseDate;
}
public String getPosterPath()
{
return posterPath;
}
public void setPosterPath(String posterPath)
{
this.posterPath = posterPath;
}
public double getPopularity()
{
return popularity;
}
public void setPopularity(double popularity)
{
this.popularity = popularity;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public boolean isVideo()
{
return video;
}
public void setVideo(boolean video)
{
this.video = video;
}
public double getVoteAverage()
{
return voteAverage;
}
public void setVoteAverage(double voteAverage)
{
this.voteAverage = voteAverage;
}
public long getVoteCount()
{
return voteCount;
}
public void setVoteCount(long voteCount)
{
this.voteCount = voteCount;
}
}
Your Json and Class variables should have the same name.
backdrop_path in Json and backdropPath in class would not work
Incase this helps for someone like me who spent half a day in trying to figure out a similar issue with gson.fromJson() returning object with null values, but when using #JsonProperty with an underscore in name and using Lombok in the model class.
My model class had a property like below and am using Lombok #Data for class
#JsonProperty(value="dsv_id")
private String dsvId;
So in my Json file I was using
"dsv_id"="123456"
Which was causing null value. The way I resolved it was changing the Json to have below ie.without the underscore. That fixed the problem for me.
"dsvId = "123456"

JsonMappingException during Json unmarshal in Spring

This is my POJO class:
public class OrdineIngressi {
private Integer spettacolo;
private Integer settore;
private Integer pv;
private List<OrdineIngresso> ingressi=new ArrayList<OrdineIngresso>();
public OrdineIngressi(Integer spettacolo, Integer settore, Integer pv,
List<OrdineIngresso> ingressi) {
super();
this.spettacolo = spettacolo;
this.settore = settore;
this.pv = pv;
this.ingressi = ingressi;
}
public OrdineIngressi() {
super();
}
public Integer getSpettacolo() {
return spettacolo;
}
public void setSpettacolo(Integer spettacolo) {
this.spettacolo = spettacolo;
}
public Integer getSettore() {
return settore;
}
public void setSettore(Integer settore) {
this.settore = settore;
}
public Integer getPv() {
return pv;
}
public void setPv(Integer pv) {
this.pv = pv;
}
public List<OrdineIngresso> getIngressi() {
return ingressi;
}
public void setIngressi(List<OrdineIngresso> ingressi) {
this.ingressi = ingressi;
}
public class OrdineIngresso {
private Integer tipoingresso;
private Integer abbonamento;
private int numero;
private Integer[] posti;
public OrdineIngresso() {
super();
}
public OrdineIngresso(Integer tipoingresso, Integer abbonamento,
int numero, Integer[] posti) {
super();
this.tipoingresso = tipoingresso;
this.abbonamento = abbonamento;
this.numero = numero;
this.posti = posti;
}
public Integer getTipoingresso() {
return tipoingresso;
}
public void setTipoingresso(Integer tipoingresso) {
this.tipoingresso = tipoingresso;
}
public Integer getAbbonamento() {
return abbonamento;
}
public void setAbbonamento(Integer abbonamento) {
this.abbonamento = abbonamento;
}
public Integer[] getPosti() {
return posti;
}
public void setPosti(Integer[] posti) {
this.posti = posti;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
}
}
This is the ajax input:
{"spettacolo":1,"settore":1,"pv":1,"ingressi":[{"tipoingresso":1,"abbonamento":null,"numero":1,"posti":[]}]}
When the Controller tries to unmarshal a json input I got this:
nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.bean.OrdineIngressi$OrdineIngresso]: can not instantiate from JSON object (need to add/enable type information?)
Why? There is a default constructor!
You're almost there, you just need to make your inner class static:
...
public static class OrdineIngresso {
private Integer tipoingresso;
...
}
IIRC it has to do with the fact that a non-args inner class constructor really isn't non-args and thus jackson doesn't have a general manner for instantiating these non-static inner classes.
Cheers,

Categories

Resources