I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nº " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("Indispnível");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
I'm trying to get the data from the arrayBundlePack after getting data from enqueue call, I'm trying to use BufferedWriter to the saved data in the arrayBundlePack & write in the txt file, but it just won't get the output I wanted.
I'm not sure if that's the way to output an arrayList model class.
Here's the code
private ArrayList<BundlePack> arrayBundlePack;
Call<BundlePackRepo> call = .............. // api content
call.enqueue(new Callback<BundlePackRepo>() {
#Override
public void onResponse(Call<BundlePackRepo> call, retrofit2.Response<BundlePackRepo> response) {
if (response.isSuccessful()) {
BundlePackRepo repos = response.body();
BundlePackRepo.bundlepacks[] bundlePacksarray;
bundlePacksarray = repos.getBundlePacks();
BundlePack bundlePack;
for (int a = 0; a < bundlePacksarray.length; a++) {
bundlePack = new BundlePack();
bundlePack.setPromotion_kit(bundlePacksarray[a].getPromotion_kit());
bundlePack.setStock_code(bundlePacksarray[a].getStock_code());
bundlePack.setIssue_ref(bundlePacksarray[a].getIssue_ref());
bundlePack.setQuantity(bundlePacksarray[a].getQuantity());
String sysMod = bundlePacksarray[a].getSys_mod();
String modifyDate = bundlePacksarray[a].getModify_dt();
try {
bundlePack.setSys_mod(df.parse(sysMod));
bundlePack.setModify_dt(df.parse(modifyDate));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
bundlePack.setStatus(bundlePacksarray[a].getStatus());
arrayBundlePack.add(bundlePack);
//Trying to put out the data to text file
String filename = "bundlepack.txt";
File txtData = new File(getApplicationContext().getFilesDir(), filename);
FileWriter txtWriter = null;
try {
txtWriter = new FileWriter(txtData);
BufferedWriter fileWriter = new BufferedWriter(txtWriter);
for (BundlePack bdpack : arrayBundlePack) {
fileWriter.write(bdpack.toString());
fileWriter.newLine();
fileWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BundlePack
#Entity
public class BundlePack{
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "promotion_kit")
private String promotion_kit;
#ColumnInfo(name = "stock_code")
private String stock_code;
#ColumnInfo(name = "issue_ref")
private String issue_ref;
#ColumnInfo(name = "quantity")
private Integer quantity;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "sys_mod")
private Date sys_mod;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "modify_dt")
private Date modify_dt;
#ColumnInfo(name = "status")
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getSys_mod() {
return sys_mod;
}
public void setSys_mod(Date sys_mod) {
this.sys_mod = sys_mod;
}
public Date getModify_dt() {
return modify_dt;
}
public void setModify_dt(Date modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "BundlePack{" +
"id=" + id +
", promotion_kit='" + promotion_kit + '\'' +
", stock_code='" + stock_code + '\'' +
", issue_ref='" + issue_ref + '\'' +
", quantity=" + quantity +
", sys_mod=" + sys_mod +
", modify_dt=" + modify_dt +
", status='" + status + '\'' +
'}';
}
}
BundlePackRepo
public class BundlePackRepo {
private String count;
private bundlepacks[] bundlepacks;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public bundlepacks[] getBundlePacks() {
return bundlepacks;
}
public void setBundlePacks(bundlepacks[] bundlePacks) {
this.bundlepacks = bundlePacks;
}
public static class bundlepacks {
#SerializedName("promotionkit")
private String promotion_kit;
#SerializedName("stock_code")
private String stock_code;
#SerializedName("iss_ref")
private String issue_ref;
#SerializedName("qty")
private int quantity;
#SerializedName("sys_mod")
private String sys_mod;
#SerializedName("modify_dt")
private String modify_dt;
#SerializedName("status")
private String status;
#SerializedName("id")
private String id;
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getSys_mod() {
return sys_mod;
}
public void setSys_mod(String sys_mod) {
this.sys_mod = sys_mod;
}
public String getModify_dt() {
return modify_dt;
}
public void setModify_dt(String modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
You are calling toString() to convert each bundlepack instance to a string for output. So you need to an override for toString to the bundlepack class. It needs to format the instance in the form that you need for your purposes.
Since you currently haven't overridden that method, your code is currently calling Object.toString() ... which only outputs the object's class name and hashcode.
Your IDE may well have a helper to generate a toString for a class, based on the fields of the class.
Trying to create object using aggregation but error shows no suitable constructor when using array to create objects. What I'm trying to understand is why wont the array identify the information implemented as I when I don't provide information on the object it is able to create an object with it's default information from both class' no-arg constructor
public class ComputerTest {
public static void main(String[] args){
Computer c[] = new Computer[5];
c[0] = new Computer("OEM", "Basic");
c[1] = new Computer("Dell", "Optiplex", "discrete", "PCIEx16", 375, "8-pin",16);
c[2] = new Computer("Lenova","IdeaCentre", "integrated", "N/A", 120, "N/A", 4);
c[3] = new Computer("HP", "Omen Obelisk", "discrete", "PCIEx8", 150,"6-pin", 8);
c[4] = new Computer("Lenovo" , "IdeaCentre", "integrated", "N/A", -110, "N/A", 2);
printComputers(c);
}
static void printComputers(Computer c[]){
for (int i=0; i<c.length; i++){
System.out.println(c[i].getInfo());
}
}
Using information from this class
public class Computer {
private String brand;
private String model;
private VideoCard VideoCard;
public Computer(){
this.setBrand("OEM");
this.setModel("Basic");
this.VideoCard = new VideoCard();
}
public Computer(String brand, String model, VideoCard VideoCard){
this.setBrand(brand);
this.setModel(model);
this.setVideoCard(VideoCard);
}
public void setBrand(String brand){
this.brand = brand;
}
public void setModel(String model){
this.model = model;
}
public void setVideoCard(VideoCard VideoCard){
this.VideoCard = VideoCard;
}
public String getBrand(){
return brand;
}
public String getModel(){
return model;
}
public VideoCard getVideoCard(){
return this.VideoCard;
}
public String getInfo(){
String info = String.format("%s " + "%s\n" + "Video Card Info:\n" + "%s\n", getBrand(), getModel(), VideoCard.getInfo());
return info;
}
which aggregates from this class
public class VideoCard {
private String type;
private String connection;
private int power;
private String extPower;
private int memory;
public VideoCard(){
this.setType("integrated");
this.setConnection("N/A");
this.setPower(100);
this.setExtPower("N/A");
this.setMemory(1);
}
public VideoCard(String type, String connection, int power, String extPower, int memory){
this.setType(type);
this.setConnection(connection);
this.setPower(power);
this.setExtPower(extPower);
this.setMemory(memory);
}
public void setType(String type){
this.type = type;
}
public void setConnection(String connection){
this.connection = connection;
}
public void setPower(int power){
if(power>= 1 && power<=300){
this.power = power;
} if(power<1) {
this.power = 75;
} if(power>300){
this.power = 200;
}
}
public void setExtPower(String extPower){
this.extPower = extPower;
}
public void setMemory(int memory){
if(memory>=1 && memory<=12){
this.memory = memory;
} if(memory<1){
this.memory = 1;
} if(memory>12){
this.memory = 12;
}
}
public String getType(){
setType(this.type);
return type;
}
public String getConnection(){
setConnection(this.connection);
return connection;
}
public int getPower(){
setPower(this.power);
return power;
}
public String getExtPower(){
setExtPower(this.extPower);
return extPower;
}
public int getMemory(){
setMemory(this.memory);
return memory;
}
public String getInfo(){
String info = String.format("Type:\t\t%s\n " + "Connection:\t%s\n " + "Power:\t\t%sW \n " + "Ext Power:\t%s\n " + "Memory:\t%dGB \n ",
getType(), getConnection(), getPower(), getExtPower(), getMemory());
return info;
}
I'm new at this.
I have something like this:
{
libri.get(i).setUtenteAssegnato(**Utente**); How do i create an Utente instance with user inputs?
}
Utente class:
package Biblioteca;
public class Utente
{
private String nome;
private String cognome;
public Utente (String unNome, String unCognome)
{
this.nome=unNome;
this.cognome=unCognome;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String toString()
{
return (this.nome + this.cognome);
}
}
This is the Libro class, with setUtenteAssegnato method:
package Biblioteca;
public class Libro
{
private int codice;
private String titolo;
private Utente utenteAssegnato;
public Libro (int unCodice, String unTitolo)
{
this.codice = unCodice;
this.titolo = unTitolo;
this.utenteAssegnato = null;
}
public Utente getUtenteAssegnato()
{
return this.utenteAssegnato;
}
public void setUtenteAssegnato(Utente utenteAssegnato)
{
this.utenteAssegnato = utenteAssegnato;
}
public int getCodice()
{
return codice;
}
public String getTitolo()
{
return titolo;
}
public String toString()
{
return (this.codice + this.titolo + this.utenteAssegnato);
}
}
This is the class i'm having problem with:
package Biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Biblioteca
{
List<Libro> libri = new ArrayList<Libro>();
List<Utente> utenti = new ArrayList<Utente>();
public Biblioteca ()
{
}
public void aggiungiUtente (String unNome, String unCognome)
{
Utente u1 = new Utente (unNome, unCognome);
utenti.add(u1);
}
public void aggiungiLibro(int unCodice, String unTitolo)
{
Libro l1 = new Libro (unCodice, unTitolo);
libri.add(l1);
}
public void creaPrestito (int unCodice, String unCognome)
{
boolean codiceTrovato = false;
boolean cognomeTrovato = false;
int i;
int j;
for (i=0; i<libri.size(); i++)
{
if (libri.get(i).getCodice() == (unCodice))
{
System.out.println("Codice trovato. ");
codiceTrovato = true;
}
else
{
System.out.println("Codice non trovato. ");
}
}
for (j=0; j<utenti.size(); j++)
{
if (utenti.get(j).getCognome().equals(unCognome))
{
System.out.println("Utente trovato. ");
cognomeTrovato = true;
}
else
{
System.out.println("Utente non trovato. ");
}
}
if (codiceTrovato && cognomeTrovato)
{
**libri.get(i).setUtenteAssegnato(Utente);**
}
}
public String toString()
{
String stampa = ", ";
for(Libro d : libri)
{
stampa += d.toString();
}
return stampa;
}
}
Basically, i don't know how to set the object in the arraylist (i) position from input (it should be 2 strings, right?)
Do i have to create another instance of Utente?
I am using JAX-RS with jersey 1.6 to consume the API. i have so far been able to consume it but now i need some specific values only.
how i am consuming api:-
ClientResponse ebpResonse = ebpResource.type("application/json")
.header(HttpHeaders.AUTHORIZATION, token)
.post(ClientResponse.class, ebpReq1);
System.out.println("ebp response is: " + ebpResonse.getEntity(String.class));
i receive response which looks like this:-
{
"code": "2075-4673",
"data": {
"requestId": 4673,
"requestCode": "2075-4673",
"fiscalYear": {
"fiscalYearId": 2075,
"fiscalYearCode": "2075/76"
},
"requestDate": 1531851300000,
"requestNdate": "2075/04/02",
"rcAgency": {
"id": 2373,
"code": "210003501",
"rcAgencyEDesc": "ABC",
"rcAgencyNDesc": " सेवा ",
"nepaliName": " सेवा",
"engishName": null
},
"status": 1,
"pan": "500127108",
"payerCode": null,
"payerEdesc": "ABC Enterprises",
"payerNdesc": null,
"payerAddress": null,
"payerPhone": null,
"totalAmount": 14000,
"createdBy": "psctest",
"createdOn": 1531851300000,
"collectedBank": null,
"collectedDate": null,
"collectedBy": null,
"token": "xxxxxxxxxxxxxxxx",
"details": [
{
"ebpNo": "4977",
"sno": 1,
"depositSlipNo": null,
"purpose": null,
"revenueHead": {
"id": 14224,
"code": "14224",
"oldCode": "14224",
"nepaliName": "शुल्क",
"englishName": "शुल्क",
"description": "शुल्क",
"nepaliDescription": "शुल्क",
"preRevenueHeadId": 0,
"status": true,
"federal": true,
"state": true,
"local": true,
"remarks": "xxxxx"
},
"remarks": "remarks",
"description": "Production",
"currency": {
"currencyId": 524,
"currencyCode": "524",
"descEnglish": "NRS",
"descNepali": "NRS"
},
"amount": 14000,
"taxAdv": false,
"taxyearId": 2074,
"dueAmount": 14000,
"createdBy": "psctest",
"createdOn": 1531894162000
}
]
},
"message": "Voucher has saved sucessfully.",
"token": "xxxxxxxxxxxxxxxxxxxx",
"status": 0
}
this response for me contains too many unnecessary information too. i need to get epbNo, token, pan in some separate variable. how can i achieve it ?
Here you go
1- Json Abstract class
package test;
import com.google.gson.Gson;
public abstract class JsonObject {
#Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
public Object toObject(String json){
Gson gson = new Gson();
return gson.fromJson(json, this.getClass());
}
}
2- Detail class
package test;
public class Detail extends JsonObject {
private String ebpNo;
private float sno;
private String depositSlipNo = null;
private String purpose = null;
RevenueHead RevenueHeadObject;
private String remarks;
private String description;
Currency CurrencyObject;
private float amount;
private boolean taxAdv;
private float taxyearId;
private float dueAmount;
private String createdBy;
private float createdOn;
// Getter Methods
public String getEbpNo() {
return ebpNo;
}
public float getSno() {
return sno;
}
public String getDepositSlipNo() {
return depositSlipNo;
}
public String getPurpose() {
return purpose;
}
public RevenueHead getRevenueHead() {
return RevenueHeadObject;
}
public String getRemarks() {
return remarks;
}
public String getDescription() {
return description;
}
public Currency getCurrency() {
return CurrencyObject;
}
public float getAmount() {
return amount;
}
public boolean getTaxAdv() {
return taxAdv;
}
public float getTaxyearId() {
return taxyearId;
}
public float getDueAmount() {
return dueAmount;
}
public String getCreatedBy() {
return createdBy;
}
public float getCreatedOn() {
return createdOn;
}
// Setter Methods
public void setEbpNo(String ebpNo) {
this.ebpNo = ebpNo;
}
public void setSno(float sno) {
this.sno = sno;
}
public void setDepositSlipNo(String depositSlipNo) {
this.depositSlipNo = depositSlipNo;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public void setRevenueHead(RevenueHead revenueHeadObject) {
this.RevenueHeadObject = revenueHeadObject;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public void setDescription(String description) {
this.description = description;
}
public void setCurrency(Currency currencyObject) {
this.CurrencyObject = currencyObject;
}
public void setAmount(float amount) {
this.amount = amount;
}
public void setTaxAdv(boolean taxAdv) {
this.taxAdv = taxAdv;
}
public void setTaxyearId(float taxyearId) {
this.taxyearId = taxyearId;
}
public void setDueAmount(float dueAmount) {
this.dueAmount = dueAmount;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public void setCreatedOn(float createdOn) {
this.createdOn = createdOn;
}
}
class Currency extends JsonObject {
private float currencyId;
private String currencyCode;
private String descEnglish;
private String descNepali;
// Getter Methods
public float getCurrencyId() {
return currencyId;
}
public String getCurrencyCode() {
return currencyCode;
}
public String getDescEnglish() {
return descEnglish;
}
public String getDescNepali() {
return descNepali;
}
// Setter Methods
public void setCurrencyId(float currencyId) {
this.currencyId = currencyId;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public void setDescEnglish(String descEnglish) {
this.descEnglish = descEnglish;
}
public void setDescNepali(String descNepali) {
this.descNepali = descNepali;
}
}
class RevenueHead extends JsonObject {
private float id;
private String code;
private String oldCode;
private String nepaliName;
private String englishName;
private String description;
private String nepaliDescription;
private float preRevenueHeadId;
private boolean status;
private boolean federal;
private boolean state;
private boolean local;
private String remarks;
// Getter Methods
public float getId() {
return id;
}
public String getCode() {
return code;
}
public String getOldCode() {
return oldCode;
}
public String getNepaliName() {
return nepaliName;
}
public String getEnglishName() {
return englishName;
}
public String getDescription() {
return description;
}
public String getNepaliDescription() {
return nepaliDescription;
}
public float getPreRevenueHeadId() {
return preRevenueHeadId;
}
public boolean getStatus() {
return status;
}
public boolean getFederal() {
return federal;
}
public boolean getState() {
return state;
}
public boolean getLocal() {
return local;
}
public String getRemarks() {
return remarks;
}
// Setter Methods
public void setId(float id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setOldCode(String oldCode) {
this.oldCode = oldCode;
}
public void setNepaliName(String nepaliName) {
this.nepaliName = nepaliName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public void setDescription(String description) {
this.description = description;
}
public void setNepaliDescription(String nepaliDescription) {
this.nepaliDescription = nepaliDescription;
}
public void setPreRevenueHeadId(float preRevenueHeadId) {
this.preRevenueHeadId = preRevenueHeadId;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setFederal(boolean federal) {
this.federal = federal;
}
public void setState(boolean state) {
this.state = state;
}
public void setLocal(boolean local) {
this.local = local;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
3- TestDTO class
/**
*
*/
package test;
import java.util.ArrayList;
/**
* #author 00990
*
*/
public class TestDTO extends JsonObject {
private String code;
Data data;
private String message;
private String token;
private float status;
// Getter Methods
public String getCode() {
return code;
}
public Data getData() {
return data;
}
public String getMessage() {
return message;
}
public String getToken() {
return token;
}
public float getStatus() {
return status;
}
// Setter Methods
public void setCode(String code) {
this.code = code;
}
public void setData(Data dataObject) {
this.data = dataObject;
}
public void setMessage(String message) {
this.message = message;
}
public void setToken(String token) {
this.token = token;
}
public void setStatus(float status) {
this.status = status;
}
public static void main(String[] args) {
String jsonObj = "{\r\n" + " \"code\": \"2075-4673\",\r\n" + " \"data\": {\r\n"
+ " \"requestId\": 4673,\r\n" + " \"requestCode\": \"2075-4673\",\r\n"
+ " \"fiscalYear\": {\r\n" + " \"fiscalYearId\": 2075,\r\n"
+ " \"fiscalYearCode\": \"2075/76\"\r\n" + " },\r\n"
+ " \"requestDate\": 1531851300000,\r\n" + " \"requestNdate\": \"2075/04/02\",\r\n"
+ " \"rcAgency\": {\r\n" + " \"id\": 2373,\r\n"
+ " \"code\": \"210003501\",\r\n" + " \"rcAgencyEDesc\": \"ABC\",\r\n"
+ " \"rcAgencyNDesc\": \" सेवा \",\r\n" + " \"nepaliName\": \" सेवा\",\r\n"
+ " \"engishName\": null\r\n" + " },\r\n" + " \"status\": 1,\r\n"
+ " \"pan\": \"500127108\",\r\n" + " \"payerCode\": null,\r\n"
+ " \"payerEdesc\": \"ABC Enterprises\",\r\n" + " \"payerNdesc\": null,\r\n"
+ " \"payerAddress\": null,\r\n" + " \"payerPhone\": null,\r\n"
+ " \"totalAmount\": 14000,\r\n" + " \"createdBy\": \"psctest\",\r\n"
+ " \"createdOn\": 1531851300000,\r\n" + " \"collectedBank\": null,\r\n"
+ " \"collectedDate\": null,\r\n" + " \"collectedBy\": null,\r\n"
+ " \"token\": \"xxxxxxxxxxxxxxxx\",\r\n" + " \"details\": [\r\n" + " {\r\n"
+ " \"ebpNo\": \"4977\",\r\n" + " \"sno\": 1,\r\n"
+ " \"depositSlipNo\": null,\r\n" + " \"purpose\": null,\r\n"
+ " \"revenueHead\": {\r\n" + " \"id\": 14224,\r\n"
+ " \"code\": \"14224\",\r\n" + " \"oldCode\": \"14224\",\r\n"
+ " \"nepaliName\": \"शुल्क\",\r\n"
+ " \"englishName\": \"शुल्क\",\r\n"
+ " \"description\": \"शुल्क\",\r\n"
+ " \"nepaliDescription\": \"शुल्क\",\r\n"
+ " \"preRevenueHeadId\": 0,\r\n" + " \"status\": true,\r\n"
+ " \"federal\": true,\r\n" + " \"state\": true,\r\n"
+ " \"local\": true,\r\n" + " \"remarks\": \"xxxxx\"\r\n"
+ " },\r\n" + " \"remarks\": \"remarks\",\r\n"
+ " \"description\": \"Production\",\r\n" + " \"currency\": {\r\n"
+ " \"currencyId\": 524,\r\n" + " \"currencyCode\": \"524\",\r\n"
+ " \"descEnglish\": \"NRS\",\r\n"
+ " \"descNepali\": \"NRS\"\r\n" + " },\r\n"
+ " \"amount\": 14000,\r\n" + " \"taxAdv\": false,\r\n"
+ " \"taxyearId\": 2074,\r\n" + " \"dueAmount\": 14000,\r\n"
+ " \"createdBy\": \"psctest\",\r\n" + " \"createdOn\": 1531894162000\r\n"
+ " }\r\n" + " ]\r\n" + " },\r\n"
+ " \"message\": \"Voucher has saved sucessfully.\",\r\n"
+ " \"token\": \"xxxxxxxxxxxxxxxxxxxx\",\r\n" + " \"status\": 0\r\n" + "}";
System.out.println("Token :" +((TestDTO) new TestDTO().toObject(jsonObj)).getToken());
System.out.println(" PAN :" +((TestDTO) new TestDTO().toObject(jsonObj)).getData().getPan());
System.out.println("EBPNo :" +((TestDTO) new TestDTO().toObject(jsonObj)).getData().getDetails().get(0).getEbpNo());
}
}
class Data extends JsonObject {
private float requestId;
private String requestCode;
FiscalYear FiscalYearObject;
private float requestDate;
private String requestNdate;
RcAgency RcAgencyObject;
private float status;
private String pan;
private String payerCode = null;
private String payerEdesc;
private String payerNdesc = null;
private String payerAddress = null;
private String payerPhone = null;
private float totalAmount;
private String createdBy;
private float createdOn;
private String collectedBank = null;
private String collectedDate = null;
private String collectedBy = null;
private String token;
ArrayList<Detail> details = new ArrayList<Detail>();
// Getter Methods
public float getRequestId() {
return requestId;
}
public ArrayList<Detail> getDetails() {
return details;
}
public void addToDetails(Detail detail) {
if (details == null) {
details = new ArrayList<Detail>();
}
this.details.add(detail);
}
public String getRequestCode() {
return requestCode;
}
public FiscalYear getFiscalYear() {
return FiscalYearObject;
}
public float getRequestDate() {
return requestDate;
}
public String getRequestNdate() {
return requestNdate;
}
public RcAgency getRcAgency() {
return RcAgencyObject;
}
public float getStatus() {
return status;
}
public String getPan() {
return pan;
}
public String getPayerCode() {
return payerCode;
}
public String getPayerEdesc() {
return payerEdesc;
}
public String getPayerNdesc() {
return payerNdesc;
}
public String getPayerAddress() {
return payerAddress;
}
public String getPayerPhone() {
return payerPhone;
}
public float getTotalAmount() {
return totalAmount;
}
public String getCreatedBy() {
return createdBy;
}
public float getCreatedOn() {
return createdOn;
}
public String getCollectedBank() {
return collectedBank;
}
public String getCollectedDate() {
return collectedDate;
}
public String getCollectedBy() {
return collectedBy;
}
public String getToken() {
return token;
}
// Setter Methods
public void setRequestId(float requestId) {
this.requestId = requestId;
}
public void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}
public void setFiscalYear(FiscalYear fiscalYearObject) {
this.FiscalYearObject = fiscalYearObject;
}
public void setRequestDate(float requestDate) {
this.requestDate = requestDate;
}
public void setRequestNdate(String requestNdate) {
this.requestNdate = requestNdate;
}
public void setRcAgency(RcAgency rcAgencyObject) {
this.RcAgencyObject = rcAgencyObject;
}
public void setStatus(float status) {
this.status = status;
}
public void setPan(String pan) {
this.pan = pan;
}
public void setPayerCode(String payerCode) {
this.payerCode = payerCode;
}
public void setPayerEdesc(String payerEdesc) {
this.payerEdesc = payerEdesc;
}
public void setPayerNdesc(String payerNdesc) {
this.payerNdesc = payerNdesc;
}
public void setPayerAddress(String payerAddress) {
this.payerAddress = payerAddress;
}
public void setPayerPhone(String payerPhone) {
this.payerPhone = payerPhone;
}
public void setTotalAmount(float totalAmount) {
this.totalAmount = totalAmount;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public void setCreatedOn(float createdOn) {
this.createdOn = createdOn;
}
public void setCollectedBank(String collectedBank) {
this.collectedBank = collectedBank;
}
public void setCollectedDate(String collectedDate) {
this.collectedDate = collectedDate;
}
public void setCollectedBy(String collectedBy) {
this.collectedBy = collectedBy;
}
public void setToken(String token) {
this.token = token;
}
}
class RcAgency extends JsonObject {
private float id;
private String code;
private String rcAgencyEDesc;
private String rcAgencyNDesc;
private String nepaliName;
private String engishName = null;
// Getter Methods
public float getId() {
return id;
}
public String getCode() {
return code;
}
public String getRcAgencyEDesc() {
return rcAgencyEDesc;
}
public String getRcAgencyNDesc() {
return rcAgencyNDesc;
}
public String getNepaliName() {
return nepaliName;
}
public String getEngishName() {
return engishName;
}
// Setter Methods
public void setId(float id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setRcAgencyEDesc(String rcAgencyEDesc) {
this.rcAgencyEDesc = rcAgencyEDesc;
}
public void setRcAgencyNDesc(String rcAgencyNDesc) {
this.rcAgencyNDesc = rcAgencyNDesc;
}
public void setNepaliName(String nepaliName) {
this.nepaliName = nepaliName;
}
public void setEngishName(String engishName) {
this.engishName = engishName;
}
}
class FiscalYear extends JsonObject {
private float fiscalYearId;
private String fiscalYearCode;
// Getter Methods
public float getFiscalYearId() {
return fiscalYearId;
}
public String getFiscalYearCode() {
return fiscalYearCode;
}
// Setter Methods
public void setFiscalYearId(float fiscalYearId) {
this.fiscalYearId = fiscalYearId;
}
public void setFiscalYearCode(String fiscalYearCode) {
this.fiscalYearCode = fiscalYearCode;
}
}
4- Run TestDTO class, here is the output
Token :xxxxxxxxxxxxxxxxxxxx PAN :500127108 EBPNo :4977
Just maintain null values in your code, and import gson-2.7.jar