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

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);
}

Related

How do I get an array value instead of reference from ObjectMapper in Jackson?

I am trying to get a result from an API response and am able to map everything except for columnHeaders, which is an array of ColumnHeaders. I am instead getting a reference to an array. The code is below.
Response Class
public class Response {
#JsonProperty("searchApiFormatVersion")
private String searchApiFormatVersion;
#JsonProperty("searchName")
private String searchName;
#JsonProperty("description")
private String description;
#JsonProperty("columnHeaders")
private ColumnHeader[] columnHeaders;
public Response(String searchApiFormatVersion, String searchName, String description,
ColumnHeader[] columnHeaders) {
this.searchApiFormatVersion = searchApiFormatVersion;
this.searchName = searchName;
this.description = description;
this.columnHeaders = columnHeaders;
}
public Response(){
}
public String getSearchApiFormatVersion() {
return searchApiFormatVersion;
}
public void setSearchApiFormatVersion(String searchApiFormatVersion) {
this.searchApiFormatVersion = searchApiFormatVersion;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ColumnHeader[] getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(ColumnHeader[] columnHeaders) {
this.columnHeaders = columnHeaders;
}
#Override
public String toString() {
return "Response{" +
"searchApiFormatVersion='" + searchApiFormatVersion + '\'' +
", searchName='" + searchName + '\'' +
", description='" + description + '\'' +
", totalRowCount=" + totalRowCount +
", returnedRowCount=" + returnedRowCount +
", startingReturnedRowNumber=" + startingReturnedRowNumber +
", basetype='" + basetype + '\'' +
", columnCount=" + columnCount +
", columnHeaders=" + columnHeaders +
'}';
}
}
ColumnHeader class
public class ColumnHeader {
#JsonProperty("text")
private String text;
#JsonProperty("dataType")
private String dataType;
#JsonProperty("hierarchy")
private int hierarchy;
#JsonProperty("parentName")
private String parentName;
#JsonProperty("isEntity")
private Boolean isEntity;
#JsonProperty("isEset")
private Boolean isEset;
public ColumnHeader(String text, String dataType, int hierarchy, String parentName, Boolean isEntity, Boolean isEset) {
this.text = text;
this.dataType = dataType;
this.hierarchy = hierarchy;
this.parentName = parentName;
this.isEntity = isEntity;
this.isEset = isEset;
}
public ColumnHeader(){
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getHierarchy() {
return hierarchy;
}
public void setHierarchy(int hierarchy) {
this.hierarchy = hierarchy;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getEntity() {
return isEntity;
}
public void setEntity(Boolean entity) {
isEntity = entity;
}
public Boolean getEset() {
return isEset;
}
public void setEset(Boolean eset) {
isEset = eset;
}
#Override
public String toString() {
return "ColumnHeader{" +
"text='" + text + '\'' +
", dataType='" + dataType + '\'' +
", hierarchy=" + hierarchy +
", parentName='" + parentName + '\'' +
", isEntity=" + isEntity +
", isEset=" + isEset +
'}';
}
}
Service Class
public class BudgetEffortResponseService {
Logger logger = LoggerFactory.getLogger(Response.class);
public Response getResponseFromStringJsonApiResponse(String stringJsonResponse) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); //Used to map objects from JSON values specified in Award under #JsonProperty annotation
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JSONObject stringJsonResponseTurnedIntoJsonObject = new JSONObject(stringJsonResponse);
logger.info("stringJsonResponseTurnedIntoJsonObject: " + stringJsonResponseTurnedIntoJsonObject);
return objectMapper.readValue(stringJsonResponseTurnedIntoJsonObject.toString(), Response.class);
}
}
Main Class
#SpringBootApplication
public class EtlApplication {
public static final String API_USERNAME = System.getenv("API_USERNAME");
public static final String API_PASSWORD = System.getenv("API_PASSWORD");
public static final String API_PREFIX = System.getenv("API_PREFIX");
public static final String API_PATH = System.getenv("API_PATH");
public static void main(String[] args) throws URISyntaxException, JsonProcessingException {
Logger logger = LoggerFactory.getLogger(EtlApplication.class);
logger.info("--------------------Starting process--------------------");
AwardRepository awardRepository = new AwardRepository();
AwardService awardService = new AwardService();
ApiResponseRowService apiResponseRowService = new ApiResponseRowService();
ApiResponseRepository apiResponseRepository = new ApiResponseRepository();
BudgetEffortResponseService budgetEffortResponseService = new BudgetEffortResponseService();
Date startDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 1).getTime();
Date endDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 2).getTime();
logger.info("============Starting BudgetEffort API pull from Huron===============");
HttpResponse<String> budgetEffortHttpResponse = apiResponseRepository.getHttpResponseFromApi(startDateForApiPull,
endDateForApiPull, 1, -1, API_PREFIX, API_PATH,
API_USERNAME, API_PASSWORD);
logger.info("BudgetEffortHttpResponse: " + budgetEffortHttpResponse);
logger.info("============End of BudgetEffort API pull from Huron===============");
//Get body of http response string
String budgetEffortResponseString = budgetEffortHttpResponse.body();
logger.info("BudgetEffortResponseString: " + budgetEffortResponseString);
Response budgetEffortResponse = budgetEffortResponseService.getResponseFromStringJsonApiResponse(budgetEffortResponseString);
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
logger.info("--------------------End of process--------------------");
}
}
The response. I'm noticing that I'm getting the reference to the array for columnHeaders and not the values. How would I get the values? Thank you.
BudgetEffortResponse: Response{searchApiFormatVersion='1.0', searchName='Personnel Details for Authorized allocations on Active Awards', description='', columnHeaders=[Lcom.example.etl.entity.budgetEffort.ColumnHeader;#7a7471ce}
The response you get is ok. And also the Array is good. The line
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
uses an indirect cast to String of the Object budgetEffortResponse. In this case all toString() methods of the objects are called. What you need to do in order to print out the Objects is to implement/add the toString() method in the class com.example.etl.entity.budgetEffort.ColumnHeader
Update:
As the toString method is already implemented, the above is partially wrong. But there is a way to use a setting of the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(budgetEffortResponse);
logger.info("BudgetEffortResponse: " + json);

Converting Paypal Checkout Transaction to a Java Object?

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.

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

Stax API XML parsing produces null results

I have been trying to get this over for a while now with little or no success. Right now, I am really out of options. I will appreciate some assistance or pointers towards the right direction.... since I believe I am not doing somethings very well.
After parsing with the code below, I have null values in most of the fields: Result{id=30c26c8a-8bdf-4d4d-8f8d-a19661f16877, name=Andriod_Office_Task, owner =generated.Owner#53d8d10a, comment=, creationTime=2016-09-09T19:30, modificationTime=2016-09-09T19:30:05+02:00, reportId=null, taskid=null, host=null, port=null, nvt=null, scanNVTVersion=null, threat=null, severity=null, description=null}
The parsing methods (other methods are excluded for brevity):
private List<Result> readDocument(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
List<Result> results = new ArrayList<>();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("result"))
results.add(readResult(parser));
break;
case XMLStreamReader.END_ELEMENT:
return results;
}
}
throw new XMLStreamException("Premature end of file");
}
public Result readResult(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
Result result = new Result();
result.setId(parser.getAttributeValue(null, "id"));
Report report = new Report();
Task task = new Task();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("name"))
result.setName(readCharacters(parser));
else if (elementName.equals("host"))
result.setHost(readCharacters(parser));
else if (elementName.equals("owner"))
result.setOwner(readOwner(parser));
else if (elementName.equals("comment"))
result.setComment(readCharacters(parser));
else if (elementName.equals("creation_time"))
result.setCreationTime(readCreationTime(parser));
else if (elementName.equals("modification_time"))
result.setModificationTime(readCharacters(parser));
else if (elementName.equals("report"))
report.setId(readReport(parser));
else if (elementName.equals("task"))
task.setId(readTask(parser));
else if (elementName.equals("user_tags"))
result.setUserTags(readUserTags(parser));
else if (elementName.equals("port"))
result.setPort(readCharacters(parser));
else if (elementName.equals("nvt"))
result.setNvt(readNvt(parser));
else if (elementName.equals("scan_nvt_version"))
result.setScanNVTVersion(readCharacters(parser));
else if (elementName.equals("threat"))
result.setThreat(readCharacters(parser));
else if (elementName.equals("severity"))
result.setSeverity(readCharacters(parser));
else if (elementName.equals("qod"))
result.setQod((Qod) readQod(parser));
else if (elementName.equals("description"))
result.setDescription(readCharacters(parser));
break;
case XMLStreamReader.END_ELEMENT:
}
return result;
}
throw new XMLStreamException("Premature end of file");
}
private String readCharacters(XMLStreamReader reader) throws XMLStreamException {
StringBuilder result = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamReader.CHARACTERS:
result.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return result.toString();
}
}
throw new XMLStreamException("Premature end of file");
}
}
The result class is below :
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#XmlAttribute
private String id;
#XmlElement
private String name;
#XmlElement
private Task task;
#XmlElement
private String comment;
#XmlElement(name = "creation_time")
String creationTime;
#XmlElement(name = "modification_time")
private String modificationTime;
// TODO user_tags
#XmlElement
private UserTags userTags;
#XmlElement
private Owner owner;
#XmlElement
private Qod qod;
/**
* // * The report the result belongs to (only when details were requested)
* //
*/
#XmlElementWrapper(name = "report")
#XmlElement(name = "reportId")
private String reportId;
#XmlElement
private String host;
#XmlElement
private String port;
#XmlElement
private NVT nvt;
#XmlElement(name = "scan_nvt_version")
private String scanNVTVersion;
#XmlElement
private String threat;
#XmlElement
private String severity;
#XmlElement
private String description;
public Result() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public UserTags getUserTags() {
return userTags;
}
public void setUserTags(UserTags userTags) {
this.userTags = userTags;
}
public Qod getQod() {
return qod;
}
public void setQod(Qod qod) {
this.qod = qod;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public NVT getNvt() {
return nvt;
}
public void setNvt(NVT nvt) {
this.nvt = nvt;
}
public String getScanNVTVersion() {
return scanNVTVersion;
}
public void setScanNVTVersion(String scanNVTVersion) {
this.scanNVTVersion = scanNVTVersion;
}
public String getThreat() {
return threat;
}
public void setThreat(String threat) {
this.threat = threat;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Result{" + "id=" + id +
", name=" + name + ", owner =" + owner +
", comment=" + comment + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime
+ ", reportId=" + reportId + ", taskid=" + task + ", host=" + host + ", port=" + port + ", nvt=" + nvt
+ ", scanNVTVersion=" + scanNVTVersion + ", threat=" + threat + ", severity=" + severity
+ ", description=" + description + '}';
}
}
<get_results_response status="200" status_text="OK">
<result id="30c26c8a-8bdf-4d4d-8f8d-a19661f16877">
<name>Trace route</name>
<owner>
<name>admin</name>
</owner>
<comment/>
<creation_time>2016-09-09T19:30:05+02:00</creation_time>
<modification_time>2016-09-09T19:30:05+02:00</modification_time>
< id="2a6d7f75-f6b7-40b2-a792-b558fada375b"/>
<task id="e59ac66b-5b59-4756-bace-37bb1106276d">
<name>Andriod_Office_Task</name>
</task>
<user_tags>
<count>0</count>re
</user_tags>
<host>172.16.53.178</host>
<port>general/tcp</port>
<nvt oid="1.3.6.1.4.1.25623.1.0.51662">
<name>Traceroute</name>
<family>General</family>
<cvss_base>0.0</cvss_base>
<cve>NOCVE</cve>
<bid>NOBID</bid>
<xref>NOXREF</xref>
<tags>cvss_base_vector=AV:N/AC:L/Au:N/C:N/I:N/A:N|qod_type=remote_banner|solution=Block unwanted packets from escaping your network.|summary=A traceroute from the scanning server to the target system was
conducted. This traceroute is provided primarily for informational
value only. In the vast majority of cases, it does not represent a
vulnerability. However, if the displayed traceroute contains any
private addresses that should not have been publicly visible, then you
have an issue you need to correct.</tags>
<cert/>
</nvt>
<scan_nvt_version>$Revision: 2837 $</scan_nvt_version>
<threat>Log</threat>
<severity>0.0</severity>
<qod>
<value>80</value>
<type>remote_banner</type>
</qod>
<description>Here is the route from 192.168.14.128 to 172.16.53.178:
192.168.14.128
172.16.53.178</description>
</result>
<filters id="">
<term>first=1 rows=-1 sort=name</term>
<keywords>
<keyword>
<column>first</column>
<relation>=</relation>
<value>1</value>
</keyword>
<keyword>
<column>rows</column>
<relation>=</relation>
<value>-1</value>
</keyword>
<keyword>
<column>sort</column>
<relation>=</relation>
<value>name</value>
</keyword>
</keywords>
</filters>
<sort>
<field>name
<order>ascending</order></field>
</sort>
<results max="-1" start="1"/>
<result_count>3444
<filtered>1</filtered>
<page>1</page></result_count>
</get_results_response>
After some research and attempts with some common xml parsing approaches, I ended up using jackson-dataformat-xml approach. While this might not be the best it gave me what I wanted with much less code. Basically, I had to adapt the annotations in the model classes as below :
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName = "results")
public class Results {
#JacksonXmlProperty(localName = "result")
#JacksonXmlElementWrapper(useWrapping = false)
public Result [] result;
public Results() {
}
public Result[] getResult() {
return result;
}
public void setResult(Result[] result) {
this.result = result;
}
#Override
public String toString() {
return "Results [result=" + Arrays.toString(result) + "]";
}
And some adaptations for the parsing class:
public class GetReportsResponseHandler extends DefaultHandler<GetReportsResponse> {
private XmlMapper mapper = new XmlMapper();
public GetReportsResponseHandler() {
super(new GetReportsResponse(), "get_reports_response");
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
}
#Override
protected void parseStartElement(XMLStreamReader parser) throws XMLStreamException, IOException {
if ("report".equals(parser.getName().toString())){
Report report = mapper.readValue(parser, Report.class);
response.addReport(report);
}

Gson conversion returning null java object

I am trying to convert json string in java bean using Gson but it is returnig null value.
public static void convert(String args) {
String json =
"{"body":{"response":{"total":"294","num":"294","filelist":[{"id":"56712","camname":"Camera1","camid":"514","start":"2016-07-08 12:00:38","end":"2016-07-08 12:03:00","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg","nvrip":"192.168.0.200:8095"},{"id":"56708","camname":"Camera1","camid":"514","start":"2016-07-08 11:58:14","end":"2016-07-08 12:00:36","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg","nvrip":"192.168.0.200:8095"},{"id":"56705","camname":"Camera1","camid":"514","start":"2016-07-08 11:55:49","end":"2016-07-08 11:58:11","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg","nvrip":"192.168.0.200:8095"},{"id":"56702","camname":"Camera1","camid":"514","start":"2016-07-08 11:53:25","end":"2016-07-08 11:55:47","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg","nvrip":"192.168.0.200:8095"},{"id":"56699","camname":"Camera1","camid":"514","start":"2016-07-08 11:51:00","end":"2016-07-08 11:53:22","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg","nvrip":"192.168.0.200:8095"}],"status":"OK"}}}";
// Now do the magic.
RecordingListResponseDTO data = new Gson().fromJson(json, RecordingListResponseDTO .class);
// Show it.
System.out.println("converted data :"+data);
}
My Bean Class is following.
RecordingListResponseDTO
public class RecordingListResponseDTO implements Serializable {
private String status;
private int total;
private int num;
List<FileListDTO> fileList;
public RecordingListResponseDTO(){
}
public RecordingListResponseDTO(String status, int total, int num, List<FileListDTO> fileList) {
this.status = status;
this.total = total;
this.num = num;
this.fileList = fileList;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List<FileListDTO> getFileList() {
return fileList;
}
public void setFileList(List<FileListDTO> fileList) {
this.fileList = fileList;
}
#Override
public String toString() {
return "RecordingListResponseDTO{" +
"status='" + status + '\'' +
", total=" + total +
", num=" + num +
", fileList=" + fileList +
'}';
}}
FileListDTO.java
public class FileListDTO {
private int id;
private String camname;
private int camid;
private Date start;
private Date end;
private int stream;
private String recReason;
private String filename;
private String snapshot;
private String nvrip;
public FileListDTO(int id, String camname, Date start, int camid, Date end, int stream, String recReason, String filename, String snapshot, String nvrip) {
this.id = id;
this.camname = camname;
this.start = start;
this.camid = camid;
this.end = end;
this.stream = stream;
this.recReason = recReason;
this.filename = filename;
this.snapshot = snapshot;
this.nvrip = nvrip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCamname() {
return camname;
}
public void setCamname(String camname) {
this.camname = camname;
}
public int getCamid() {
return camid;
}
public void setCamid(int camid) {
this.camid = camid;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public int getStream() {
return stream;
}
public void setStream(int stream) {
this.stream = stream;
}
public String getRecReason() {
return recReason;
}
public void setRecReason(String recReason) {
this.recReason = recReason;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getSnapshot() {
return snapshot;
}
public void setSnapshot(String snapshot) {
this.snapshot = snapshot;
}
public String getNvrip() {
return nvrip;
}
public void setNvrip(String nvrip) {
this.nvrip = nvrip;
}
#Override
public String toString() {
return "FileListDTO{" +
"id=" + id +
", camname='" + camname + '\'' +
", camid=" + camid +
", start=" + start +
", end=" + end +
", stream=" + stream +
", recReason='" + recReason + '\'' +
", filename='" + filename + '\'' +
", snapshot='" + snapshot + '\'' +
", nvrip='" + nvrip + '\'' +
'}';
}}
I am getting null value after converting Json string to Java object.
what I am doing wrong please suggest me.
Thank in advance.
Prerequisites:
Following JSON has been used:
{
"body":{
"response":{
"total":294,
"num":294,
"filelist":[
{
"id":56712,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 12:00:38",
"end":"2016-07-08 12:03:00",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56708,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:58:14",
"end":"2016-07-08 12:00:36",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56705,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:55:49",
"end":"2016-07-08 11:58:11",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56702,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:53:25",
"end":"2016-07-08 11:55:47",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56699,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:51:00",
"end":"2016-07-08 11:53:22",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg",
"nvrip":"192.168.0.200:8095"
}
],
"status":"OK"
}
}
}
Step 1:
Modify the declaration of private List<FileListDTO> fileList in RecordingListResponseDTO.java as follows:
#SerializedName("filelist")
private List<FileListDTO> fileList
Step 2:
Define following class MyDateTypeAdapter.java:
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class MyDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private DateFormat dateFormat;
public MyDateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
#Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
#Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Step 3:
Modify the method convert(String args) as follows:
public static void convert(String args) {
JsonParser parser = new JsonParser();
String json = parser.parse(args)
.getAsJsonObject()
.getAsJsonObject("body")
.getAsJsonObject("response")
.toString();
// Now do the magic.
RecordingListResponseDTO data = new GsonBuilder()
.registerTypeAdapter(Date.class, new MyDateTypeAdapter())
.create().fromJson(json, RecordingListResponseDTO.class);
// Show it.
System.out.println("converted data :"+data);
}
For testing purpose, you may try storing the JSON in a file i.e. D:/test.json and call the method by:
String json = new String(Files.readAllBytes(Paths.get("D:/test.json")));
convert(json);
something you need to change the models class like,
Initially in your json response data contains "body" tag that's represents to object, initially you need to create the class for object tag,then all data contains inside your "body" tag, so parse all data inside from body data,
may help this code,
public class RecordingListResponseDTO implements Serializable {
Recordinglist body;
public class Recordinglist(){
Recordresponse response;
public class Recordresponse(){
String total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
}
}

Categories