Converting Paypal Checkout Transaction to a Java Object? - java

I've been working on a Paypal JSON to Java object converter, using Gson. But, it doesn't generate a full Java object. Seems like this conversion would have already been done, but I couldn't find anything.
My technique is to take the Paypal JSON, do replacements of their non-Java element names, then parse that into a Java object that I've defined.
Here's what the Gson looks like:
Gson gson = new GsonBuilder().serializeNulls().create();
JSONObjFromPaypalTrx jsonPaypalTrx = gson.fromJson(paypalTrx, JSONObjFromPaypalTrx.class);
logger.debug("jsonPaypalTrx: " +jsonPaypalTrx);
paypalTrx is the Paypal JSON after the element names are replaced:
paypalTrx: {"id":"PAYID-LXJIHMI92J52777N04488909","intent":"Sale","state":"approved","cart":"25M35194DL227451S","createTime":"2019-11-18T11:42:41Z","Payer":{"paymentMethod":"paypal","status":"VERIFIED","PayerInfo":{"email":"sb-cject591397#personal.example.com","firstName":"John","middleName":"John","lastName":"Doe","payerId":"5V25373K45VBE","countryCode":"US","ShippingAddress":{"recipientName":"John Doe","line1":"1 Main St","city":"San Jose","state":"CA","postalCode":"95131","countryCode":"US"}}},"Transactions":[{"Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}},"ItemList":{},"RelatedResources":[{"Sale":{"id":"80E26736585579458","state":"completed","paymentMode":"INSTANT_TRANSFER","protectionEligibility":"ELIGIBLE","parentPayment":"PAYID-LXJIHMI92J52777N04488909","createTime":"2019-11-18T11:43:00Z","updateTime":"2019-11-18T11:43:00Z","Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}}}}]}]}
Here's the Java object I've defined:
package com.example;
import java.util.List;
/**
* This JSON Object was derived from a Paypal transaction string.
*/
public class JSONObjFromPaypalTrx{
private String id;
private String intent;
private String state;
private String cart;
private String createTime;
private Payer payer;
private List<Transactions> transactions;
public JSONObjFromPaypalTrx() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getIntent(){
return intent;
}
public void setIntent(String input){
this.intent = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getCart(){
return cart;
}
public void setCart(String input){
this.cart = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public Payer getPayer(){
return payer;
}
public void setPayer(Payer input){
this.payer = input;
}
public List<Transactions> getTransactions(){
return transactions;
}
public void setTransactions(List<Transactions> input){
this.transactions = input;
}
public static class ShippingAddress{
private String recipientName;
private String line1;
private String city;
private String state;
private String postalCode;
private String countryCode;
public ShippingAddress() {
}
public String getRecipientName(){
return recipientName;
}
public void setRecipientName(String input){
this.recipientName = input;
}
public String getLine1(){
return line1;
}
public void setLine1(String input){
this.line1 = input;
}
public String getCity(){
return city;
}
public void setCity(String input){
this.city = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPostalCode(){
return postalCode;
}
public void setPostalCode(String input){
this.postalCode = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
#Override
public String toString() {
return "ShippingAddress [recipientName: " + recipientName + ", line1: " + line1 + ", city: " + city
+ ", state: " + state + ", postalCode: " + postalCode + ", countryCode: " + countryCode + "]";
}
}
public static class PayerInfo{
private String email;
private String firstName;
private String middleName;
private String lastName;
private String payerId;
private String countryCode;
private ShippingAddress shippingAddress;
public PayerInfo() {
}
public String getEmail(){
return email;
}
public void setEmail(String input){
this.email = input;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getMiddleName(){
return middleName;
}
public void setMiddleName(String input){
this.middleName = input;
}
public String getLastName(){
return lastName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getPayerId(){
return payerId;
}
public void setPayerId(String input){
this.payerId = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
public ShippingAddress getShippingAddress(){
return shippingAddress;
}
public void setShippingAddress(ShippingAddress input){
this.shippingAddress = input;
}
#Override
public String toString() {
return "PayerInfo [email: " + email + ", firstName: " + firstName + ", middleName: " + middleName
+ ", lastName: " + lastName + ", payerId: " + payerId + ", countryCode: " + countryCode
+ ", shippingAddress: " + shippingAddress + "]";
}
}
public static class Payer{
private String paymentMethod;
private String status;
private PayerInfo payerInfo;
public Payer() {
}
public String getPaymentMethod(){
return paymentMethod;
}
public void setPaymentMethod(String input){
this.paymentMethod = input;
}
public String getStatus(){
return status;
}
public void setStatus(String input){
this.status = input;
}
public PayerInfo getPayerInfo(){
return payerInfo;
}
public void setPayerInfo(PayerInfo input){
this.payerInfo = input;
}
#Override
public String toString() {
return "Payer [paymentMethod: " + paymentMethod + ", status: " + status + ", payerInfo: " + payerInfo + "]";
}
}
public static class Amount{
private String total;
private String currency;
private Details details;
public Amount() {
}
public String getTotal(){
return total;
}
public void setTotal(String input){
this.total = input;
}
public String getCurrency(){
return currency;
}
public void setCurrency(String input){
this.currency = input;
}
public Details getDetails(){
return details;
}
public void setDetails(Details input){
this.details = input;
}
#Override
public String toString() {
return "Amount [total: " + total + ", currency: " + currency + ", details: " + details + "]";
}
}
public static class ItemList{
public ItemList() {
}
}
public static class Details{
private String subtotal;
private String shipping;
private String handlingFee;
private String insurance;
private String shippingDiscount;
public Details() {
}
public String getSubtotal(){
return subtotal;
}
public void setSubtotal(String input){
this.subtotal = input;
}
public String getShipping(){
return shipping;
}
public void setShipping(String input){
this.shipping = input;
}
public String getHandlingFee(){
return handlingFee;
}
public void setHandlingFee(String input){
this.handlingFee = input;
}
public String getInsurance(){
return insurance;
}
public void setInsurance(String input){
this.insurance = input;
}
public String getShippingDiscount(){
return shippingDiscount;
}
public void setShippingDiscount(String input){
this.shippingDiscount = input;
}
#Override
public String toString() {
return "Details [subtotal: " + subtotal + ", shipping: " + shipping + ", handlingFee: " + handlingFee
+ ", insurance: " + insurance + ", shippingDiscount: " + shippingDiscount + "]";
}
}
public static class Sale{
private String id;
private String state;
private String paymentMode;
private String protectionEligibility;
private String parentPayment;
private String createTime;
private String updateTime;
private Amount amount;
public Sale() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPaymentMode(){
return paymentMode;
}
public void setPaymentMode(String input){
this.paymentMode = input;
}
public String getProtectionEligibility(){
return protectionEligibility;
}
public void setProtectionEligibility(String input){
this.protectionEligibility = input;
}
public String getParentPayment(){
return parentPayment;
}
public void setParentPayment(String input){
this.parentPayment = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public String getUpdateTime(){
return updateTime;
}
public void setUpdateTime(String input){
this.updateTime = input;
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
#Override
public String toString() {
return "Sale [id: " + id + ", state: " + state + ", paymentMode: " + paymentMode + ", protectionEligibility: "
+ protectionEligibility + ", parentPayment: " + parentPayment + ", createTime: " + createTime
+ ", updateTime: " + updateTime + ", amount: " + amount + "]";
}
}
public static class RelatedResources{
private Sale sale;
public RelatedResources() {
}
public Sale getSale(){
return sale;
}
public void setSale(Sale input){
this.sale = input;
}
#Override
public String toString() {
return "RelatedResources [sale: " + sale + "]";
}
}
public static class Transactions{
private Amount amount;
private ItemList itemList;
private List<RelatedResources> relatedResources;
public Transactions() {
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
public ItemList getItemList(){
return itemList;
}
public void setItemList(ItemList input){
this.itemList = input;
}
public List<RelatedResources> getRelatedResources(){
return relatedResources;
}
public void setRelatedResources(List<RelatedResources> input){
this.relatedResources = input;
}
#Override
public String toString() {
return "Transactions [amount: " + amount + ", itemList: " + itemList + ", relatedResources: "
+ relatedResources + "]";
}
}
#Override
public String toString() {
return "JSONObjFromPaypalTrx [id: " + id + ", intent: " + intent + ", state: " + state + ", cart: " + cart
+ ", createTime: " + createTime + ", payer: " + payer + ", transactions: " + transactions + "]";
}
}
Here's a log of jsonPaypalTrx:
jsonPaypalTrx: JSONObjFromPaypalTrx [id: PAYID-LXJIHMI92J52777N04488909, intent: Sale, state: approved, cart: 25M35194DL227451S, createTime: 2019-11-18T11:42:41Z, payer: null, transactions: null]
Is the incomplete jsonPaypalTrx due to my use of inner classes inside JSONObjFromPaypalTrx? Splitting each inner class into separate Java files would be awkward for me to do.
Thanks for helping.
Bob

Given JSON payload uses mixed naming convention: camel case and UPPER_CAMEL_CASE for JSON Objects. So, you need to implement your own FieldNamingStrategy:
class PayPalFieldNamingStrategy implements FieldNamingStrategy {
#Override
public String translateName(Field f) {
return f.getType() == String.class ? f.getName() : FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(f);
}
}
And register it like below:
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(new PayPalFieldNamingStrategy())
.create();
Or, for each object declare name like below:
#SerializedName("Payer")
private Payer payer;

Make your member classes static so that they don't need an outer class reference when they're constructed.
Like: public static class ShippingAddress.
Gson likely doesn't know how to constructor inner classes, but it will know how to construct static member classes.

Related

How to get the covid info of a country with java, JSON

I am making a java file in which you enter the country and then it shows you the covid-19 info of that country. The site which I am using is https://covid19.mathdro.id/api/countries/
here i want it such that the user enter the country and it adds the countries name to the website eg if the user entered India it should do this
https://covid19.mathdro.id/api/countries/India
Any help would be neccessary, Thanks
You can use Retrofit to call the APIs
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.Response;
public class Retrofit_Example {
public static void main(String[] args) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid19.mathdro.id/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
Service service = retrofit.create(Service.class);
Call<Response1> responseCall = service.getData("India");
try {
Response<Response1> response = responseCall.execute();
Response1 apiResponse = response.body();
System.out.println(apiResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You will have to create POJOs from the JSON response coming from the api first and also the retrofit client.
POJO for respone
public class Response1 {
private Confirmed confirmed;
private Deaths deaths;
private String lastUpdate;
private Recovered recovered;
public Confirmed getConfirmed() {
return confirmed;
}
public void setConfirmed(Confirmed confirmed) {
this.confirmed = confirmed;
}
public Deaths getDeaths() {
return deaths;
}
public void setDeaths(Deaths deaths) {
this.deaths = deaths;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Recovered getRecovered() {
return recovered;
}
public void setRecovered(Recovered recovered) {
this.recovered = recovered;
}
#Override
public String toString() {
return "Response1{" +
"confirmed=" + confirmed +
", deaths=" + deaths +
", lastUpdate='" + lastUpdate + '\'' +
", recovered=" + recovered +
'}';
}
}
public class Recovered {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Recovered{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Deaths {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Deaths{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Confirmed {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Confirmed{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
Retrofit Client
public interface Service {
#GET("/api/countries/{country}")
public Call<Response1> getData(#Path("country")String country);
}

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

Using toString() method from child class

Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?
The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}

Need Help to resolve : could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize

Below is the stacktrace of the error:
org.springframework.orm.hibernate3.HibernateSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:217)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:240)
Below is my POJO class :
public static final class MemberName implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 3832626162173359411L;
private String firstname;
private String lastname;
private String gender;
private String dexterity;
private String matchPreference;
private String tournamentEntry;
/*private Double rating;
private Double minRating=Double.valueOf(2.5);
private Double maxRating=Double.valueOf(5.0);*/
private Integer rating=null;
private Integer minRating=null;
private Integer maxRating=Integer.valueOf(5);
private Integer maxHandicap = Integer.valueOf(100);//Integer.valueOf(6);
private Integer minHandicap = null;
public MemberName() {
}
public String getFirstname() { return this.firstname; }
public void setFirstname(String name) { this.firstname = name; }
public String getLastname() { return this.lastname; }
public void setLastname(String name) { this.lastname = name; }
public Integer getMaxHandicap() { return this.maxHandicap; }
public void setMaxHandcap(Integer d) { this.maxHandicap = d; }
public Integer getMinHandicap() { return this.minHandicap; }
public void setMinHandcap(Integer d) { this.minHandicap = d; }
public String getGender() { return this.gender;}
public void setGender(String gender) {this.gender = gender;}
public String getDexterity() {return this.dexterity;}
public void setDexterity(String dexterity) {this.dexterity = dexterity;}
public String getMatchPreference() {return this.matchPreference;}
public void setMatchPreference(String matchPreference) {this.matchPreference = matchPreference;}
public String getTournamentEntry() {return this.tournamentEntry;}
public void setTournamentEntry(String tournamentEntry) {this.tournamentEntry = tournamentEntry;}
public Integer getRating() {return this.rating;}
public void setRating(Integer r) {this.rating = r;}
public Integer getMinRating() {return this.minRating;}
public void setMinRating(Integer minR) {this.minRating = minR;}
public Integer getMaxRating() {return this.maxRating;}
public void setMaxRating(Integer maxR) {this.maxRating = maxR;}
public boolean isValidSearch()
{
return (null != this.firstname) ||
(null != this.lastname) ||
(null != this.maxRating) ||
(null != this.minRating)||
(null != this.rating)||
(null != this.gender) ||
(null != this.dexterity) ||
(null != this.matchPreference)||
(null != this.tournamentEntry);
}
#Override
public String toString() {
return "MemberName [firstname=" + firstname + ", lastname="
+ lastname + ", gender=" + gender + ", dexterity="
+ dexterity + ", matchPreference=" + matchPreference
+ ", tournamentEntry=" + tournamentEntry + ", rating="
+ rating + ", minRating=" + minRating + ", maxRating="
+ maxRating + "]";
}
}
and I'm using hibernate 3 to fetch the data from User table which is a hibernate pojo class-
public List<User> findUsers(Long cityId, String firstName, String
lastName,
String gender, Double rating, Double minRating, Double maxRating,
String dexterity, String matchPreference, String tournamentEntry) {
StringBuilder sb = new StringBuilder();
if (null != cityId) {
sb.append("u.registeredCity.id=").append(cityId).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isNotEmpty(firstName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.firstName like '").append(firstName).append("%' ");
}
if (isNotEmpty(lastName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.lastName like '").append(lastName).append("%'");
}
sb.append(" order by u.firstName, u.lastName");
if (sb.length() > 0) {
sb.insert(0, "where "); //$NON-NLS-1$
}
sb.insert(0, "from User u "); //$NON-NLS-1$
this.log.info("SQL from findUsers method is::"+sb.toString());
return getHibernateTemplate().find(sb.toString());
}

how to get the specific value of JSON response from JAX-RS ?

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

Categories