How to get response from Array in retrofit? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Here is my response. I don't know how to create Response Model for this type of response model
[{"id":"4","templateName":"FUP 100","dataUsage":"100 GB","price":236,"groupName":"","bandwidthName":""},{"id":"19","templateName":"FUP200","dataUsage":"200 GB","price":299.72,"groupName":"","bandwidthName":""}]

your retrofit call must be a list of your object not just the object
your object is like that
public class MyClass
{
private String id;
private String groupName;
private String price;
private String dataUsage;
private String bandwidthName;
private String templateName;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getGroupName ()
{
return groupName;
}
public void setGroupName (String groupName)
{
this.groupName = groupName;
}
public String getPrice ()
{
return price;
}
public void setPrice (String price)
{
this.price = price;
}
public String getDataUsage ()
{
return dataUsage;
}
public void setDataUsage (String dataUsage)
{
this.dataUsage = dataUsage;
}
public String getBandwidthName ()
{
return bandwidthName;
}
public void setBandwidthName (String bandwidthName)
{
this.bandwidthName = bandwidthName;
}
public String getTemplateName ()
{
return templateName;
}
public void setTemplateName (String templateName)
{
this.templateName = templateName;
}
#Override
public String toString()
{
return "MyClass [id = "+id+", groupName = "+groupName+", price = "+price+", dataUsage = "+dataUsage+", bandwidthName = "+bandwidthName+", templateName = "+templateName+"]";
}
}
kotlin :
class MyClass {
var id:String
var groupName:String
var price:String
var dataUsage:String
var bandwidthName:String
var templateName:String
public override fun toString():String {
return "MyClass [id = " + id + ", groupName = " + groupName + ", price = " + price + ", dataUsage = " + dataUsage + ", bandwidthName = " + bandwidthName + ", templateName = " + templateName + "]"
}
}
there are online tools to help you http://pojo.sodhanalibrary.com/

public class Response {
#SerializedName("id")
#Expose
private String id;
#SerializedName("templateName")
#Expose
private String templateName;
#SerializedName("dataUsage")
#Expose
private String dataUsage;
#SerializedName("price")
#Expose
private Double price;
#SerializedName("groupName")
#Expose
private String groupName;
#SerializedName("bandwidthName")
#Expose
private String bandwidthName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getDataUsage() {
return dataUsage;
}
public void setDataUsage(String dataUsage) {
this.dataUsage = dataUsage;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getBandwidthName() {
return bandwidthName;
}
public void setBandwidthName(String bandwidthName) {
this.bandwidthName = bandwidthName;
}
}
Then Create ArrayList because your response start with array :
#Headers("Content-Type:application/json")
#GET("your_api")
Call<ArrayList<Response>> api();

Related

JSON is returning a list type object when it has 1 position as object and not as a list

I have a list of objects instantiated in a return class in a service's response. But when this list has 1 position, it is returning as an object and not as a list. can anybody help me?
#XmlRootElement(name = "exame")
public class ExameVO implements Serializable {
private static final long serialVersionUID = -5840337332057658386L;
private long id;
#NotNull
private String cpf;
#NotNull
private String dataNascimento;
#NotNull
private int tipoExame;
#NotNull
private String excluido;
private List<ExameArquivoVO> resultadoExameArquivos;
private String observacao;
private String dataInclusao;
public ExameVO() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public int getTipoExame() {
return tipoExame;
}
public void setTipoExame(int tipoExame) {
this.tipoExame = tipoExame;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getExcluido() {
return excluido;
}
public void setExcluido(String excluido) {
this.excluido = excluido;
}
public List<ExameArquivoVO> getResultadoExameArquivos() {
return resultadoExameArquivos;
}
public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
this.resultadoExameArquivos = resultadoExameArquivos;
}
public String getDataInclusao() {
return dataInclusao;
}
public void setDataInclusao(String dataInclusao) {
this.dataInclusao = dataInclusao;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "ResultadoExameVO [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
+ tipoExame + ", observacao=" + observacao + ", excluido=" + excluido + ", dataInclusao=" + dataInclusao
+ ", resultadoExameArquivos=" + resultadoExameArquivos + "]";
}
}
#Override
public List<ExameVO> listarExames(String cpf, String dtNascimento, Long tipoExame) throws WebServiceException {
List<ExameVO> examesVO = new ArrayList<ExameVO>();
try {
examesVO = exameDAO.listarExames(cpf, dtNascimento, tipoExame);
if(!examesVO.isEmpty()) {
for(ExameVO exameVO : examesVO) {
exameVO.setResultadoExameArquivos(new ArrayList<ExameArquivoVO>());
exameVO.getResultadoExameArquivos().addAll(exameDAO.listarExameArquivos(exameVO.getId()));
}
}
return examesVO;
} catch (Exception e) {
throw new WebServiceException(e);
}
}
Response to postman: Notice that there is 1 object that has 2 objects inside the file list and another object that has 1 and it returns as an object and not as a list with 1 object.

My List<Object> is not being passed correctly as object of my ModelAndView

In my Spring Controller I have:
List<User> Users = this.userService.UsersList();
mav = new ModelAndView("users");
mav.addObject("Users", Users);
When I iterate over Users I can see all the attributes values of every element of my list.
This is my .jsp code:
<c:forEach items="${Users}" var="usr">
${usr}
</c:forEach>
This is my users class:
#Entity
#Table(name="usuario")
public class User implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#JoinColumn(name = "id_perfil")
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Perfil perfil;
#Column(name="nombre")
private String nombre;
#Column(name="usuario")
private String usuario;
#Column(name="contrasenia")
private String contrasenia;
#Column(name="correo")
private String correo;
#Column(name="telefono")
private String telefono;
#Column(name="imagen_perfil")
private String imagen_perfil;
#Column(name="intento_fallido")
private int intento_fallido;
#Column(name="intranet_id")
private Integer intranet_id;
#Column(name="intranet_notaria")
private Integer intranet_notaria;
#Column(name="intranet_token_codigo")
private String intranet_token_codigo;
#Column(name="intranet_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date intranet_token_fecha;
#Column(name="tesoreria_token_codigo")
private String tesoreria_token_codigo;
#Column(name="tesoreria_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date tesoreria_token_fecha;
#Column(name="activo")
private int activo;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Perfil getPerfil() { return perfil; }
public void setPerfil(Perfil perfil) { this.perfil = perfil; }
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getUsuario() { return usuario; }
public void setUsuario(String usuario) { this.usuario = usuario; }
public String getContrasenia() { return contrasenia; }
public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getTelefono() { return telefono; }
public void setTelefono(String telefono) { this.telefono = telefono; }
public String getImagenPerfil() { return imagen_perfil; }
public void setImagenPerfil(String imagen_perfil) { this.imagen_perfil = imagen_perfil; }
public int getIntentoFallido() { return intento_fallido; }
public void setIntentoFallido(int intento_fallido) { this.intento_fallido = intento_fallido; }
public Integer getIntranetId() { return intranet_id; }
public void setIntranetId(Integer intranet_id) { this.intranet_id = intranet_id; }
public Integer getIntranetNotaria() { return intranet_notaria; }
public void setIntranetNotaria(Integer intranet_notaria) { this.intranet_notaria = intranet_notaria; }
public String getIntranetTokenCodigo() { return intranet_token_codigo; }
public void setIntranetTokenCodigo(String intranet_token_codigo) { this.intranet_token_codigo = intranet_token_codigo; }
public Date getIntranetTokenFecha() { return intranet_token_fecha; }
public void setIntranetTokenFecha(Date intranet_token_fecha) { this.intranet_token_fecha = intranet_token_fecha; }
public String getTesoreriaTokenCodigo() { return tesoreria_token_codigo; }
public void setTesoreriaTokenCodigo(String tesoreria_token_codigo) { this.tesoreria_token_codigo = tesoreria_token_codigo; }
public Date getTesoreriaTokenFecha() { return tesoreria_token_fecha; }
public void setTesoreriaTokenFecha(Date tesoreria_token_fecha) { this.tesoreria_token_fecha = tesoreria_token_fecha; }
public int getActivo() { return activo; }
public void setActivo(int activo) { this.activo = activo; }
#Override
public String toString() {
return "Id:" + id + ", " + "Perfil:" + perfil.getNombre() + ", " + "Id_Perfil:" + perfil.getId() + ", " + "Nombre:" + nombre + ", " + "Usuario:" + usuario + ", " + "Correo:" + correo + ", " + "Teléfono:" + telefono + ", " + "Image_Perfil:" + imagen_perfil + ", " + "Intranet_Id:" + intranet_id + ", " + "Intranet_Notaria:" + intranet_notaria + ", " + "Activo:" + activo;
}
}
The problem is that ${usr} is only displaying some of my attributes, but not all! I need to display all the attributes in my jsp.
Try using camelCase notation if you are not doing so. For example instead of ${usr.imagen_perfil} use ${usr.imagenPerfil}. I think it will be expecting to use the object getters getImagenPerfil().

Getting and putting Json into Pojo class

So I've made an app that should be able to search for an artist off the Spotify API. The response returns a 200 code. But the returned object is null. Meaning that either the response code should be 204 or that something is wrong with my class. The class is made with pojo and seems right.
I can't seem to figure out what is wrong.
Here are the code.
Artist Class
public class Artists {
#SerializedName("href")
#Expose
private String href;
#SerializedName("items")
#Expose
private List<Item> items;
#SerializedName("limit")
#Expose
private Integer limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private Integer offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total")
#Expose
private Integer total;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Object getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
#Override
public String toString() {
return "Artists{" +
"href='" + href + '\'' +
", items=" + items +
", limit=" + limit +
", next='" + next + '\'' +
", offset=" + offset +
", previous='" + previous + '\'' +
", total=" + total +
'}';
}
Item Class
public class Item {
#SerializedName("external_urls")
#Expose
private ExternalUrls externalUrls;
#SerializedName("followers")
#Expose
private Followers followers;
#SerializedName("genres")
#Expose
private List<String> genres;
#SerializedName("href")
#Expose
private String href;
#SerializedName("id")
#Expose
private String id;
#SerializedName("images")
#Expose
private List<Image> images;
#SerializedName("name")
#Expose
private String name;
#SerializedName("popularity")
#Expose
private Integer popularity;
#SerializedName("type")
#Expose
private String type;
#SerializedName("uri")
#Expose
private String uri;
public ExternalUrls getExternalUrls() {
return externalUrls;
}
public void setExternalUrls(ExternalUrls externalUrls) {
this.externalUrls = externalUrls;
}
public Followers getFollowers() {
return followers;
}
public void setFollowers(Followers followers) {
this.followers = followers;
}
public List<String> getGenres() {
return genres;
}
public void setGenres(List<String> genres) {
this.genres = genres;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPopularity() {
return popularity;
}
public void setPopularity(Integer popularity) {
this.popularity = popularity;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
#Override
public String toString() {
return "Item{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
'}';
}
MainActivity
public void searchForArtist(View view) {
String q = "Justin Bieber";
TrackService trackService = ApiUtils.getTrackService();
Call<Artists> artistSearch = trackService.SearchForArtist("Bearer " + AuthToken, Accept, contentType, q, type, market, limit, offset);
Log.d("TEST", artistSearch.request().url().toString());
Log.d("TEST", " " + artistSearch.request().headers());
Log.d("Tokens", AuthToken);
Log.d("Tokens", " " + RefreshToken);
artistSearch.enqueue(new Callback<Artists>() {
#Override
public void onResponse(Call<Artists> call, Response<Artists> response) {
if (response.isSuccessful()) {
if (response.body().getItems() != null) {
Item artists = response.body().getItems().get(0);
artistID = artists.getId();
Toast.makeText(MainActivity.this, "Yeehaw", Toast.LENGTH_LONG).show();
searchForTracks(artistID);
} else {
Toast.makeText(MainActivity.this, "No content in Items", Toast.LENGTH_LONG).show();
Log.d("BODY",response.body().toString());
}
} else {
String message = "Problem " + response.code() + " " + response.body();
Log.d("Tracks", message);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Artists> call, Throwable t) {
Toast.makeText(MainActivity.this, "REEEEEEEE", Toast.LENGTH_LONG).show();
}
});
}

Cannot convert List object to List<clasname>

Cannot convert from List to List
When trying to use a list in my Test method, I am getting an error with adding a list to an ArrayList.
This is the code that the error is in:
#Test
public void testGetAllModules_OK() throws Exception {
List<Modules> modules = Arrays.asList(new Modules(1, "C02103", "Architecture", 1, true));
when(modRepo.findAll()).thenReturn(modules);
mockMvc.perform(get("/Modules"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].ModuleCode", is ("C02103")))
.andExpect(jsonPath("$[0].title", is ("Architecture")))
.andExpect(jsonPath("$.[0].semester", is (1)))
.andExpect(jsonPath("$[0].CoreModule", is(true)));
verify(modRepo, times(1)).findAll();
}
Here is the creation of Module class
#Entity
public class Modules implements Iterable<Modules> {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ModuleId;
private String ModuleCode;
private String title;
private int semester;
private boolean CoreModule;
ArrayList<String> lecture = new ArrayList<String>();
ArrayList<String> mod = new ArrayList<String>();
public Modules(int ModuleId, String ModuleCode, String title, int semester, boolean CoreModule) {
this.ModuleId = ModuleId;
this.ModuleCode = ModuleCode;
this.title = title;
this.semester = semester;
this.CoreModule = CoreModule;
}
public Modules(String ModuleCode, String title, int semester, boolean CoreModule)
{
this.ModuleCode = ModuleCode;
this.title = title;
this.semester = semester;
this.CoreModule = CoreModule;
}
public Modules(String ModuleCode,String title, boolean CoreModule )
{
this.ModuleCode = ModuleCode;
this.title = title;
this.CoreModule = CoreModule;
}
public Modules()
{}
/*
* #ManyToOne(fetch = FetchType.EAGER, optional = false)
*
* #OneToMany(mappedBy = "module", fetch = FetchType.EAGER, cascade =
* CascadeType.ALL)
*/
public int getModuleId() {
return ModuleId;
}
public void setModuleId(int moduleId) {
ModuleId = moduleId;
}
public String getModuleCode() {
return ModuleCode;
}
public void setModuleCode(String moduleCode) {
ModuleCode = moduleCode;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
public boolean isCoreModule() {
return CoreModule;
}
public void setCoreModule(boolean coreModule) {
CoreModule = coreModule;
}
#Override
public String toString() {
return "Modules [ModuleId=" + ModuleId + ", ModuleCode=" + ModuleCode + ", title=" + title + ", semester="
+ semester + ", CoreModule=" + CoreModule + "]";
}
}
Any help would be very appreciated, as I'm getting the same error with similar test methods

Cannot set data to Java Model

I have a model below which i use to add my data and get it's properties when a user selects an option. Unfortunately i am unable to get the logic right. Kindly help with the best way to set data to a model using an array.
Unfortunately i get the error Data cannot be applied to Data[]
Model
public class Data
{
private String isVerified;
private String providerType;
private String modifiedAt;
private String modifiedBy;
private String provider;
private String id;
private String accountNumber;
private String accountName;
private String createdBy;
private String isDefault;
private String createdAt;
private String userId;
private String providerId;
public String getIsVerified ()
{
return isVerified;
}
public void setIsVerified (String isVerified)
{
this.isVerified = isVerified;
}
public String getProviderType ()
{
return providerType;
}
public void setProviderType (String providerType)
{
this.providerType = providerType;
}
public String getModifiedAt ()
{
return modifiedAt;
}
public void setModifiedAt (String modifiedAt)
{
this.modifiedAt = modifiedAt;
}
public String getModifiedBy ()
{
return modifiedBy;
}
public void setModifiedBy (String modifiedBy)
{
this.modifiedBy = modifiedBy;
}
public String getProvider ()
{
return provider;
}
public void setProvider (String provider)
{
this.provider = provider;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getAccountNumber ()
{
return accountNumber;
}
public void setAccountNumber (String accountNumber)
{
this.accountNumber = accountNumber;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getCreatedBy ()
{
return createdBy;
}
public void setCreatedBy (String createdBy)
{
this.createdBy = createdBy;
}
public String getIsDefault ()
{
return isDefault;
}
public void setIsDefault (String isDefault)
{
this.isDefault = isDefault;
}
public String getCreatedAt ()
{
return createdAt;
}
public void setCreatedAt (String createdAt)
{
this.createdAt = createdAt;
}
public String getUserId ()
{
return userId;
}
public void setUserId (String userId)
{
this.userId = userId;
}
public String getProviderId ()
{
return providerId;
}
public void setProviderId (String providerId)
{
this.providerId = providerId;
}
#Override
public String toString()
{
return "ClassPojo [isVerified = "+isVerified+", providerType = "+providerType+", modifiedAt = "+modifiedAt+", modifiedBy = "+modifiedBy+", provider = "+provider+", id = "+id+", accountNumber = "+accountNumber+", accountName = "+accountName+", createdBy = "+createdBy+", isDefault = "+isDefault+", createdAt = "+createdAt+", userId = "+userId+", providerId = "+providerId+"]";
}
}
Below is my method to add data to the model
private void addToWallets(Data walletData) {
Data wallet = new Data();
wallet.setId(walletData.getId());
wallet.setAccountNumber(walletData.getAccountNumber());
wallets.add(wallet);
}
I add the response from the server to my method that i created to add data to the model:
if (response.isSuccess()){
loading.dismiss();
Data[] wallets = response.body().getData();
addToWallets(wallets);
}
An array of Data can't be converted to a single Data object.
I suppose that this is what you want:
Data[] wallets = response.body().getData();
for (Data wallet : wallets) {
addToWallets(wallet);
}

Categories

Resources