I need to consume a third party RESTful API. This is my controller class:
#Controller
public class BrokerController {
#RequestMapping(value = "/broker", method = RequestMethod.POST)
public #ResponseBody MyPojo brokers(#RequestBody BrokerRequest brokerRequest){
RestTemplate restTemplate = new RestTemplate();
final String uri = "http://www.nepalipaisa.com/Modules/MarketMovers/Services/MarketMoversServices.asmx/GetTopBrokers";
MyPojo myPojo = restTemplate.postForObject(uri,brokerRequest,MyPojo.class);
return myPojo;
}
}
Edited:- My pojo class:
public class MyPojo {
private String __type;
private Integer RowTotal;
private Integer StockID;
private Object CodedCompany;
private Object ClosingPrice;
private Integer Amount;
private Integer PreviousClosing;
private Integer DifferenceRS;
private Object Symbol;
private Integer Price;
private Integer Diff;
private Integer PercentageDiff;
private Object Volume;
private Integer TotalTurnOverAmount;
private String FirmName;
private Integer BrokerID;
private String BrokerCode;
private Integer TotalTransactions;
private Object Traded;
private Object MaxPrice;
private Object MinPrice;
private Object OpeningPrice;
private Object TotalShare;
private Integer NoOfTransaction;
private Integer Purchase;
private Integer Sales;
private Integer Matching;
public String get__type() {
return __type;
}
public void set__type(String __type) {
this.__type = __type;
}
public Integer getRowTotal() {
return RowTotal;
}
public void setRowTotal(Integer rowTotal) {
this.RowTotal = rowTotal;
}
public Integer getStockID() {
return StockID;
}
public void setStockID(Integer stockID) {
this.StockID = stockID;
}
public Object getCodedCompany() {
return CodedCompany;
}
public void setCodedCompany(Object codedCompany) {
this.CodedCompany = codedCompany;
}
public Object getClosingPrice() {
return ClosingPrice;
}
public void setClosingPrice(Object closingPrice) {
this.ClosingPrice = closingPrice;
}
public Integer getAmount() {
return Amount;
}
public void setAmount(Integer amount) {
this.Amount = amount;
}
public Integer getPreviousClosing() {
return PreviousClosing;
}
public void setPreviousClosing(Integer previousClosing) {
this.PreviousClosing = previousClosing;
}
public Integer getDifferenceRS() {
return DifferenceRS;
}
public void setDifferenceRS(Integer differenceRS) {
this.DifferenceRS = differenceRS;
}
public Object getSymbol() {
return Symbol;
}
public void setSymbol(Object symbol) {
this.Symbol = symbol;
}
public Integer getPrice() {
return Price;
}
public void setPrice(Integer price) {
this.Price = price;
}
public Integer getDiff() {
return Diff;
}
public void setDiff(Integer diff) {
this.Diff = diff;
}
public Integer getPercentageDiff() {
return PercentageDiff;
}
public void setPercentageDiff(Integer percentageDiff) {
this.PercentageDiff = percentageDiff;
}
public Object getVolume() {
return Volume;
}
public void setVolume(Object volume) {
this.Volume = volume;
}
public Integer getTotalTurnOverAmount() {
return TotalTurnOverAmount;
}
public void setTotalTurnOverAmount(Integer totalTurnOverAmount) {
this.TotalTurnOverAmount = totalTurnOverAmount;
}
public String getFirmName() {
return FirmName;
}
public void setFirmName(String firmName) {
this.FirmName = firmName;
}
public Integer getBrokerID() {
return BrokerID;
}
public void setBrokerID(Integer brokerID) {
this.BrokerID = brokerID;
}
public String getBrokerCode() {
return BrokerCode;
}
public void setBrokerCode(String brokerCode) {
this.BrokerCode = brokerCode;
}
public Integer getTotalTransactions() {
return TotalTransactions;
}
public void setTotalTransactions(Integer totalTransactions) {
this.TotalTransactions = totalTransactions;
}
public Object getTraded() {
return Traded;
}
public void setTraded(Object traded) {
this.Traded = traded;
}
public Object getMaxPrice() {
return MaxPrice;
}
public void setMaxPrice(Object maxPrice) {
this.MaxPrice = maxPrice;
}
public Object getMinPrice() {
return MinPrice;
}
public void setMinPrice(Object minPrice) {
this.MinPrice = minPrice;
}
public Object getOpeningPrice() {
return OpeningPrice;
}
public void setOpeningPrice(Object openingPrice) {
this.OpeningPrice = openingPrice;
}
public Object getTotalShare() {
return TotalShare;
}
public void setTotalShare(Object totalShare) {
this.TotalShare = totalShare;
}
public Integer getNoOfTransaction() {
return NoOfTransaction;
}
public void setNoOfTransaction(Integer noOfTransaction) {
this.NoOfTransaction = noOfTransaction;
}
public Integer getPurchase() {
return Purchase;
}
public void setPurchase(Integer purchase) {
this.Purchase = purchase;
}
public Integer getSales() {
return Sales;
}
public void setSales(Integer sales) {
this.Sales = sales;
}
public Integer getMatching() {
return Matching;
}
public void setMatching(Integer matching) {
this.Matching = matching;
}
}
The JSON iI need to consume, i.e the exact result given below:
{
"d": [
{
"__type": "SageFrame.MarketMovers.MarketInfo",
"RowTotal": 0,
"StockID": 0,
"CodedCompany": null,
"ClosingPrice": null,
"Amount": 0,
"PreviousClosing": 0,
"DifferenceRS": 0,
"Symbol": null,
"Price": 0,
"Diff": 0,
"PercentageDiff": 0,
"Volume": null,
"TotalTurnOverAmount": 109969058,
"FirmName": "Vision Securities Pvt. Ltd.",
"BrokerID": 0,
"BrokerCode": "34",
"TotalTransactions": 0,
"Traded": null,
"MaxPrice": null,
"MinPrice": null,
"OpeningPrice": null,
"TotalShare": null,
"NoOfTransaction": 0,
"Purchase": 70691939,
"Sales": 39277119,
"Matching": 6381555
},
{
"__type": "SageFrame.MarketMovers.MarketInfo",
"RowTotal": 0,
"StockID": 0,
"CodedCompany": null,
"ClosingPrice": null,
"Amount": 0,
"PreviousClosing": 0,
"DifferenceRS": 0,
"Symbol": null,
"Price": 0,
"Diff": 0,
"PercentageDiff": 0,
"Volume": null,
"TotalTurnOverAmount": 104830489,
"FirmName": "Online Securities Pvt. Ltd.",
"BrokerID": 0,
"BrokerCode": "49",
"TotalTransactions": 0,
"Traded": null,
"MaxPrice": null,
"MinPrice": null,
"OpeningPrice": null,
"TotalShare": null,
"NoOfTransaction": 0,
"Purchase": 51927902,
"Sales": 52902587,
"Matching": 3049044
}
]
}
Currently when I send a POST request with two parameters
{
"offset":"1",
"limit":"2000"
}
I can get the result given above. Now I need to return the same result but through my own controller. The above controller returns MyPojo class with null value on every properties.
You can always try to put the results from the third party API into a Map.
Map results = restTemplate.postForObject(uri,brokerRequest, Map.class);
Or you can create a new pojo just for that third part API.
ThirdPartyPojo results = restTemplate.postForObject(uri,brokerRequest, ThirdPartyPojo.class);
Right now the issue is that your pojo MyPojo is not compatible with the response of 3rd party API.
Your pojo should be something like following.
-----------------------------------com.example.D.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
public class D {
private String type;
private Integer rowTotal;
private Integer stockID;
private Object codedCompany;
private Object closingPrice;
private Integer amount;
private Integer previousClosing;
private Integer differenceRS;
private Object symbol;
private Integer price;
private Integer diff;
private Integer percentageDiff;
private Object volume;
private Integer totalTurnOverAmount;
private String firmName;
private Integer brokerID;
private String brokerCode;
private Integer totalTransactions;
private Object traded;
private Object maxPrice;
private Object minPrice;
private Object openingPrice;
private Object totalShare;
private Integer noOfTransaction;
private Integer purchase;
private Integer sales;
private Integer matching;
// Getter .. Setter//
}
-----------------------------------com.example.MyPojo.java-----------------------------------
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
public class Example {
#JsonProperty("d")
private List<D> d = null;
// Getter ... Setter
}
Or simply you can use Map.
This can be accomplished easily not even requiring you to provide custom mappings or whatever like that and guarantee that your controller wil provide the same response (not the same headers, though):
#RestController
final class Controller {
// Both RestTemplate and URI instances can be cached
private static final RestTemplate restTemplate = new RestTemplate();
private static final URI testUri = URI.create("http://www.nepalipaisa.com/Modules/MarketMovers/Services/MarketMoversServices.asmx/GetTopBrokers");
// I'm using GET just to simplify the testing using a web browser
#RequestMapping(method = GET, value = "/")
public void post(final ServletResponse response)
throws IOException {
// Create a POST request entity
final RequestEntity<?> requestEntity = new RequestEntity<>(getRequest(0, 10), POST, testUri);
// And send the request to the remote server
final ResponseEntity<Resource> responseEntity = restTemplate.exchange(requestEntity, Resource.class);
// Now just copy the response input stream to the output stream of this controller
try ( final InputStream inputStream = responseEntity.getBody().getInputStream() ) {
// Or provide HttpServletResponse via the controller method to be able to configure the response more accurately
StreamUtils.copy(inputStream, response.getOutputStream());
}
}
private static Object getRequest(final long offset, final long limit) {
final Map<String, Object> request = new HashMap<>();
request.put("offset", offset);
request.put("limit", limit);
return request;
}
}
The remote server can respond with a non-successful response code, so you can also have a custom controller advice to handle RestTemplate exceptions:
#ControllerAdvice
final class ExceptionControllerAdvice {
#ExceptionHandler(HttpServerErrorException.class)
#ResponseBody
public ResponseEntity<?> handleHttpServerErrorException(final HttpServerErrorException ex) {
return new ResponseEntity<Object>("Bad gateway: " + ex.getMessage(), BAD_GATEWAY);
}
}
Related
Hi i am creating a service of Invoice PO to get the json reponse after verification from classes of service package.
First I have created a model package and classes according to json.
InvoiceRequest is like this--
package com.InvoicePO.newmodel;
import java.util.List;
public class InvoiceRequest {
private List<Records> records;
public List<Records> getRecords() {
return records;
}
public void setRecords(List<Records> records) {
this.records = records;
}
}
Records Class--
package com.InvoicePO.newmodel;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Records {
private String Vecv_plant;
private String DBM_Plant;
private String VECV_SO;
private String DBM_PO;
private String VBELN;
private String FKDAT;
private String LRDATE;
private String PFCHARGE;
private String OCHARGE;
private String DISC;
private String TAXTYPE;
private String TAX;
private String TAXAMT;
private String INVAMT;
private String WAERK;
private String INVCNT;
private String ODN;
private List<LineItemTable> lineItemTables;
public String getVecv_plant() {
return Vecv_plant;
}
public void setVecv_plant(String vecv_plant) {
Vecv_plant = vecv_plant;
}
public String getDBM_Plant() {
return DBM_Plant;
}
public void setDBM_Plant(String dBM_Plant) {
DBM_Plant = dBM_Plant;
}
public String getVECV_SO() {
return VECV_SO;
}
public void setVECV_SO(String vECV_SO) {
VECV_SO = vECV_SO;
}
public String getDBM_PO() {
return DBM_PO;
}
public void setDBM_PO(String dBM_PO) {
DBM_PO = dBM_PO;
}
public String getVBELN() {
return VBELN;
}
public void setVBELN(String vBELN) {
VBELN = vBELN;
}
public String getFKDAT() {
return FKDAT;
}
public void setFKDAT(String fKDAT) {
FKDAT = fKDAT;
}
public String getLRDATE() {
return LRDATE;
}
public void setLRDATE(String lRDATE) {
LRDATE = lRDATE;
}
public String getPFCHARGE() {
return PFCHARGE;
}
public void setPFCHARGE(String pFCHARGE) {
PFCHARGE = pFCHARGE;
}
public String getOCHARGE() {
return OCHARGE;
}
public void setOCHARGE(String oCHARGE) {
OCHARGE = oCHARGE;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
LineItemTable--
package com.InvoicePO.newmodel;
public class LineItemTable {
private String VBELN1;
private String DEALER1;
private String POSEX;
private String MATNR;
private String INVQTY;
private String RATE;
private String TOTAL;
private String DISC;
private String TAXTYPE;
private String PURCH_NO;
private String PURCH_DATE;
private String SALES_NO;
private String PGIX;
public String getVBELN1() {
return VBELN1;
}
public void setVBELN1(String vBELN1) {
VBELN1 = vBELN1;
}
public String getDEALER1() {
return DEALER1;
}
public void setDEALER1(String dEALER1) {
DEALER1 = dEALER1;
}
public String getPOSEX() {
return POSEX;
}
public void setPOSEX(String pOSEX) {
POSEX = pOSEX;
}
public String getMATNR() {
return MATNR;
}
public void setMATNR(String mATNR) {
MATNR = mATNR;
}
public String getINVQTY() {
return INVQTY;
}
public void setINVQTY(String iNVQTY) {
INVQTY = iNVQTY;
}
public String getRATE() {
return RATE;
}
public void setRATE(String rATE) {
RATE = rATE;
}
public String getTOTAL() {
return TOTAL;
}
public void setTOTAL(String tOTAL) {
TOTAL = tOTAL;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
}
public void setTAXTYPE(String tAXTYPE) {
TAXTYPE = tAXTYPE;
}
public String getPURCH_NO() {
return PURCH_NO;
}
public void setPURCH_NO(String pURCH_NO) {
PURCH_NO = pURCH_NO;
}
public String getPURCH_DATE() {
return PURCH_DATE;
}
public void setPURCH_DATE(String pURCH_DATE) {
PURCH_DATE = pURCH_DATE;
}
public String getSALES_NO() {
return SALES_NO;
}
public void setSALES_NO(String sALES_NO) {
SALES_NO = sALES_NO;
}
public String getPGIX() {
return PGIX;
}
public void setPGIX(String pGIX) {
PGIX = pGIX;
}
}
Invoice Controller--
package com.InvoicePO.controller;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.InvoicePO.newmodel.InvoiceRequest;
import com.InvoicePO.service.DTRECCPOVCPLINVOICE;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records.LineItemTable;
import com.InvoicePO.service.SISVCPLINVOICETOECCPO;
import com.InvoicePO.service.SISVCPLINVOICETOECCPOService;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
#RestController
public class InvoiceController {
public static String getJsonFromObject(Object obj) {
ObjectMapper Obj = new ObjectMapper();
Obj.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Writer strWriter = new StringWriter();
try {
Obj.writeValue(strWriter,obj);
return strWriter.toString();
} catch (Exception e) {
return "";
}
}
#RequestMapping(value = "/invoicepo", method=RequestMethod.POST)
public #ResponseBody DTRECCPOVCPLINVOICE VerficationDetails(#RequestBody InvoiceRequest data) {
System.out.println("/Data Recieved" + getJsonFromObject(data));
DTRECCPOVCPLINVOICE response = null;
DTSVCPLINVOICETOECCPO soapobj = new DTSVCPLINVOICETOECCPO();
List<Records> objc = new ArrayList<>();
for(com.InvoicePO.newmodel.Records records : data.getRecords())
{
// RECORD records = data;
Records rec = new Records();
rec.setVecvPlant(records.getVecv_plant());
rec.setDBMPlant(records.getDBM_Plant());
rec.setVECVSO(records.getVECV_SO());
rec.setDBMPO(records.getDBM_PO());
rec.setVBELN(records.getVBELN());
rec.setFKDAT(records.getFKDAT());
rec.setLRDATE(records.getLRDATE());
rec.setPFCHARGE(records.getPFCHARGE());
rec.setOCHARGE(records.getOCHARGE());
rec.setDISC(records.getDISC());
rec.setTAXTYPE(records.getTAXTYPE());
rec.setTAX(records.getTAX());
rec.setTAXAMT(records.getTAXAMT());
rec.setINVAMT(records.getINVAMT());
rec.setWAERK(records.getWAERK());
rec.setINVCNT(records.getINVCNT());
rec.setODN(records.getODN());
List<LineItemTable> line = new ArrayList<>();
for(com.InvoicePO.newmodel.LineItemTable table : records.getLineItemTables()) {
// LineItemTable table = data;
LineItemTable lin = new LineItemTable();
lin.setDEALER1(table.getDEALER1());
lin.setPOSEX(table.getPOSEX());
lin.setMATNR(table.getMATNR());
lin.setINVQTY(table.getINVQTY());
lin.setRATE(table.getRATE());
lin.setTOTAL(table.getTOTAL());
lin.setDISC(table.getDISC());
lin.setTAXTYPE(table.getTAXTYPE());
lin.setPURCHNO(table.getPURCH_NO());
lin.setPURCHDATE(table.getPURCH_DATE());
lin.setSALESNO(table.getSALES_NO());
lin.setPGIX(table.getPGIX());
line.add(lin);
}
rec.setLineItemTable(line);
rec.setLineItemTable(line);
objc.add(rec);
}
System.out.println("\nRequest for PI:" +getJsonFromObject(soapobj));
SISVCPLINVOICETOECCPOService sisservice= new SISVCPLINVOICETOECCPOService();
SISVCPLINVOICETOECCPO port = sisservice.getHTTPSPort();
// DTSVCPLINVOICETOECCPO eccpo = new DTSVCPLINVOICETOECCPO();
// eccpo.setRecords(objc);
BindingProvider provider = (BindingProvider)port;
provider.getRequestContext().put("javax.xml.ws.security.auth.username", "pisuper");
provider.getRequestContext().put("javax.xml.ws.security.auth.password", "Xidvecv#123");
response = port.siSVCPLINVOICETOECCPO(soapobj);
System.out.println("\nResponse for PI:" +getJsonFromObject(soapobj));
return response ;
}
}
The json i am hitting in Postman --
{
"Records": {
"Vecv_plant": 1110,
"DBM_Plant": "C001",
"VECV_SO": 5110000139,
"DBM_PO": "5900000069",
"VBELN": 91297393,
"FKDAT": 20221208,
"LRDATE": 0,
"PFCHARGE": 0,
"OCHARGE": 0,
"DISC": 0,
"TAXTYPE": "IGST",
"TAX": 0,
"TAXAMT": 364.04,
"INVAMT": 2386.46,
"WAERK": "INR",
"INVCNT": 0,
"ODN": "IN9220800004",
"LineItemTable": [
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 10,
"MATNR": "IM300124L",
"INVQTY": 9,
"RATE": 2022,
"TOTAL": 2386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
},
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 20,
"MATNR": "IM300262L",
"INVQTY": 8,
"RATE": 1030,
"TOTAL": 1386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
}
]
}
}
The error I am getting = Cannot invoke java.util.List.iterator() because the return value of com.InvoicePO.newmodel.InvoiceRequest.getRecords() is null
I want to send array of objects like this to Spring REST Controller:
{
"measureList": [
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:51.787535Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
},
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:53.254309Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
}
]
}
I have created NewMeausurePackageDto like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
import java.util.List;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getNewMeasureListDto() {
return measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
NewMeasureDto class:
package com.weather.server.domain.dto;
public class NewMeasureDto {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
//station_id
public NewMeasureDto() {
}
private NewMeasureDto(Builder builder){
apiKey = builder.apiKey;
stationId = builder.stationId;
date = builder.date;
temp = builder.temp;
humidity = builder.humidity;
pressure = builder.pressure;
pm25 = builder.pm25;
pm10 = builder.pm10;
pm25Corr = builder.pm25Corr;
}
public String getApiKey() {
return apiKey;
}
public String getStationID() {
return stationId;
}
public String getDate() {
return date;
}
public String getTemp() {
return temp;
}
public String getHumidity() {
return humidity;
}
public String getPressure() {
return pressure;
}
public String getPm25() {
return pm25;
}
public String getPm10() {
return pm10;
}
public String getPm25Corr() {
return pm25Corr;
}
public static final class Builder {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
public Builder() {
}
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
public Builder stationID(String stationId) {
this.stationId = stationId;
return this;
}
public Builder date(String date) {
this.date = date;
return this;
}
public Builder temp(String temp) {
this.temp = temp;
return this;
}
public Builder humidity(String humidity) {
this.humidity = humidity;
return this;
}
public Builder pressure(String pressure){
this.pressure = pressure;
return this;
}
public Builder pm25(String pm25){
this.pm25 = pm25;
return this;
}
public Builder pm10(String pm10){
this.pm10 = pm10;
return this;
}
public Builder pm25Corr(String pm25Corr){
this.pm25Corr = pm25Corr;
return this;
}
public NewMeasureDto build() {
return new NewMeasureDto(this);
}
}
}
And request mapping in RestController:
#PostMapping(value="/new-measure-package") //addStation id
public ResponseEntity<Void> newMeasure(#RequestBody NewMeasurePackageDto measureList){
//if api key is valid
return measureService.saveMeasurePackage(measureList.getNewMeasureListDto()) ? new ResponseEntity<>(HttpStatus.OK) :
new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
With this code all I got is error about null measureList in Service function when trying to iterate over the list. I tried changing #RequestBody to
List<NewMeasureDto> measureList, and to Map<String, NewMeasureDto> measureList but still measureList is null or empty.
Thanks to ShaharT suggestion I found the answer.
There was missing setter in NewMeasurePackageDto, the class should look like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getMeasureList() {
return measureList;
}
public void setMeasureList(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
Conclusion is: when dealing with object of arrays in JSON, there must be setter method for variable storing list in DTO.
My problem: when I do an #Post in Postman I get data back from the prices, but not kitten data.
I enter the following:
{
"name": "Frizzle",
"dateOfBirth": "2019-07-27",
"weight": 7.1,
"breed": "Birman",
"firstVaccination": "yes",
"secondVaccination": "yes",
"breedPrice": 8000,
"firstVaccinationPrice": 80.50,
"secondVaccinationPrice": 80.10
}
And this is what I get back in Postman:
{
"id": 3,
"name": null,
"dateOfBirth": null,
"weight": 0.0,
"breed": null,
"firstVaccination": null,
"secondVaccination": null,
"fileUpload": null,
"price": {
"id": 3,
"broadPrice": 8000.0,
"firstVaccinationPrice": 80.5,
"secondVaccinationPrice": 80.1,
"totalPrice": 8160.6
}
}
I've tried changing the code in several places, but I can't figure out why it outputs the price part and not the kitten data part. I want it to output the kitten data. So basically what I want is for him to reverse it, return data of the kittens and give data of the prices that are null.
My files look like this.
Kitten.java
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(name = "kittens")
public class Kitten {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
private String name;
#NotNull
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#NotNull
#Column
private double weight;
#NotNull
#Column(name = "breed")
private String breed;
#Column(name = "first_vaccination")
private String firstVaccination;
#Column(name = "second_vaccination")
private String secondVaccination;
#OneToOne(mappedBy = "kitten")
private FileUpload fileUpload;
#OneToOne(fetch = FetchType.LAZY,
mappedBy = "kitten")
private Price price;
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
}
public Kitten() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public FileUpload getFileUpload() {
return fileUpload;
}
public void setFileUpload(FileUpload fileUpload) {
this.fileUpload = fileUpload;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
}
Price.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.NotNull;
import javax.persistence.*;
#Entity
#Table(name = "prices")
public class Price {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "breed_price")
private double breedPrice;
#Column(name = "first_vaccination_price")
private double firstVaccinationPrice;
#Column(name = "second_vaccination_price")
private double secondVaccinationPrice;
#JsonIgnore
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true)
#JoinColumn(name = "kitten_id")
private Kitten kitten;
public Price() {
}
public Price(double breedPrice, double firstVaccinationPrice, double secondVaccinationPrice) {
this.breedPrice = breedPrice;
this.firstVaccinationPrice = firstVaccinationPrice;
this.secondVaccinationPrice = secondVaccinationPrice;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
public Kitten getKitten() {
return kitten;
}
public void setKitten(Kitten kitten) {
this.kitten = kitten;
}
public Double getTotalPrice() {
return this.getBreedPrice() + this.getFirstVaccinationPrice() + this.getSecondVaccinationPrice();
}
}
KittenBuilder.java
import nl.danielle.cattery.payload.KittenRequest;
import java.time.LocalDate;
public class KittenBuilder {
//Kitten
private String name;
private LocalDate dateOfBirth;
private double weight;
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public KittenBuilder(KittenRequest kittenRequest) {
this.name = kittenRequest.getName();
this.dateOfBirth = kittenRequest.getDateOfBirth();
this.weight = kittenRequest.getWeight();
this.breed = kittenRequest.getBreed();
this.firstVaccination = kittenRequest.getFirstVaccination();
this.secondVaccination = kittenRequest.getSecondVaccination();
this.breedPrice = kittenRequest.getBreedPrice();
this.firstVaccinationPrice = kittenRequest.getFirstVaccinationPrice();
this.secondVaccinationPrice = kittenRequest.getSecondVaccinationPrice();
}
public Kitten buildKitten() {
return new Kitten(name, dateOfBirth, weight, breed, firstVaccination, secondVaccination);
}
public Price buildPrice() {
return new Price(breedPrice, firstVaccinationPrice, secondVaccinationPrice);
}
}
KittenRequest.java
import com.sun.istack.NotNull;
import java.time.LocalDate;
public class KittenRequest {
//Kitten
#NotNull
private String name;
#NotNull
private LocalDate dateOfBirth;
#NotNull
private double weight;
#NotNull
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
#NotNull
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
}
KittenController.java
import nl.danielle.cattery.model.FileUpload;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.payload.ResponseMessage;
import nl.danielle.cattery.service.FileStorageServiceImpl;
import nl.danielle.cattery.service.KittenService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
#RestController
#RequestMapping(value = "/kittens")
public class KittenController {
final KittenService kittenService;
final FileStorageServiceImpl storageService;
public KittenController(KittenService kittenService, FileStorageServiceImpl storageService) {
this.kittenService = kittenService;
this.storageService = storageService;
}
#GetMapping(value = "")
public ResponseEntity<Object> getKittens() {
return ResponseEntity.ok().body(kittenService.getKittens());
}
#GetMapping(value = "/{id}")
public ResponseEntity<Object> getKitten(#PathVariable("id") long id) {
return ResponseEntity.ok().body(kittenService.getKittenById(id));
}
#PostMapping(value = "/add")
public ResponseEntity<Object> saveKitten(#RequestBody KittenRequest kitten) {
long newId = kittenService.saveKitten(kitten);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newId).toUri();
return ResponseEntity.created(location).build();
}
#PutMapping(value = "/{id}")
public ResponseEntity<Object> updateKitten(#PathVariable("id") long id, #RequestBody KittenRequest kitten) {
kittenService.updateKitten(id, kitten);
return ResponseEntity.noContent().build();
}
#PutMapping(value = "/{id}/price")
public ResponseEntity<Object> updatePrice(#PathVariable("id") long id, #RequestBody KittenRequest price) {
kittenService.updatePrice(id, price);
return ResponseEntity.noContent().build();
}
#DeleteMapping(value = "/{id}")
public ResponseEntity<Object> deleteKitten(#PathVariable("id") long id) {
kittenService.deleteKitten(id);
return ResponseEntity.noContent().build();
}
#PostMapping("/upload/kittenid/{id}")
public ResponseEntity<ResponseMessage> uploadFile(#PathVariable long id, #RequestParam("file") MultipartFile file) {
try {
storageService.store(file, id);
String message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
String message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
#GetMapping("/download/{id}")
public ResponseEntity<byte[]> getFileById(#PathVariable("id") String id) {
FileUpload fileUpload = storageService.getFileById(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
.body(fileUpload.getData());
}
}
KittenService.java
package nl.danielle.cattery.service;
import nl.danielle.cattery.exceptions.DatabaseErrorException;
import nl.danielle.cattery.exceptions.RecordNotFoundException;
import nl.danielle.cattery.model.Kitten;
import nl.danielle.cattery.model.KittenBuilder;
import nl.danielle.cattery.model.Price;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.repository.KittenRepository;
import nl.danielle.cattery.repository.PriceRepository;
import org.springframework.stereotype.Service;
import java.util.Collection;
#Service
public class KittenServiceImpl implements KittenService {
final KittenRepository kittenRepository;
final PriceRepository priceRepository;
public KittenServiceImpl(KittenRepository kittenRepository, PriceRepository priceRepository) {
this.kittenRepository = kittenRepository;
this.priceRepository = priceRepository;
}
#Override
public Collection<Kitten> getKittens() {
return kittenRepository.findAll();
}
#Override
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException();
}
return kittenRepository.findById(id).orElse(null);
}
#Override
public long saveKitten(KittenRequest kittenRequest) {
Kitten newKitten = new KittenBuilder(kittenRequest).buildKitten();
Price newPrice = new KittenBuilder(kittenRequest).buildPrice();
Price savedPrice = priceRepository.save(newPrice);
newKitten.setPrice(savedPrice);
newPrice.setKitten(newKitten);
return kittenRepository.save(newKitten).getId();
}
#Override
public void updateKitten(long id, KittenRequest kitten) {
if (kittenRepository.existsById(id)) {
try {
Kitten existingKitten = kittenRepository.findById(id).orElse(null);
existingKitten.setName(kitten.getName());
existingKitten.setDateOfBirth(kitten.getDateOfBirth());
existingKitten.setWeight(kitten.getWeight());
existingKitten.setBreed(kitten.getBreed());
existingKitten.setFirstVaccination(kitten.getFirstVaccination());
existingKitten.setSecondVaccination(kitten.getSecondVaccination());
kittenRepository.save(existingKitten);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void updatePrice(long id, KittenRequest price) {
if (priceRepository.existsById(id)) {
try {
Price existingPrice = priceRepository.findById(id).orElse(null);
existingPrice.setBreedPrice(price.getBreedPrice());
existingPrice.setFirstVaccinationPrice(price.getFirstVaccinationPrice());
existingPrice.setSecondVaccinationPrice(price.getSecondVaccinationPrice());
priceRepository.save(existingPrice);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void deleteKitten(long id) {
kittenRepository.deleteById(id);
}
}
I have a lot to say about your code here, but let's see what's the main problem here. The problem is simple if you look at your KittenBuilder you create a Kitten using this builder but your Kitten constructor is empty.
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.weight = weight;
this.breed = breed;
this.firstVaccination = firstVaccination;
this.secondVaccination = secondVaccination;
}
This will populate the Kitten object and you're ready to go.
Some advices about your code
If you wonder why it's saving the null values when you specified the null constraints is that recent version of spring boot don't include the validation starter in the web starter, you have to include it yourself.
In you pom.xml add the following dependecy:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
And you have to include the annotation #Transactional to your services to make your operations atomic, for example in your create kitten method you want to persist the price and the kitten atomically.
#Service
#Transactional
class KittenServiceImpl implementes ...
And one the best practices also, is to not use your entites directly in your controllers, use DTO (Data Transfer Object), so you map the properties you want from your entity to your DTO (this way you can include only your kitten properties and leave the price entity).
And last bonus:
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException("");
}
return kittenRepository.findById(id).orElse(null);
}
This can be simplified to:
public Kitten getKittenById(long id) {
return kittenRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
}
I'm trying to parse a JSON like this
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"customer_id": "some-customer-id",
"id": 5,
"is_active": true,
"product_code": "some-product-code",
"resource_uri": "/api/v1/aws-marketplace/5/",
"support_subscription_id": "22"
}
]
}
generated for http://www.jsonschema2pojo.org I got his Java clases
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AwsMarketplace {
#SerializedName("meta")
#Expose
private Meta meta;
#SerializedName("objects")
#Expose
private List<Object> objects = null;
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
public List<Object> getObjects() {
return objects;
}
public void setObjects(List<Object> objects) {
this.objects = objects;
}
}
Meta class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Meta {
#SerializedName("limit")
#Expose
private int limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private int offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total_count")
#Expose
private int totalCount;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
Object class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Object {
#SerializedName("customer_id")
#Expose
private String customerId;
#SerializedName("id")
#Expose
private int id;
#SerializedName("is_active")
#Expose
private boolean isActive;
#SerializedName("product_code")
#Expose
private String productCode;
#SerializedName("resource_uri")
#Expose
private String resourceUri;
#SerializedName("support_subscription_id")
#Expose
private String supportSubscriptionId;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isIsActive() {
return isActive;
}
public void setIsActive(boolean isActive) {
this.isActive = isActive;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getResourceUri() {
return resourceUri;
}
public void setResourceUri(String resourceUri) {
this.resourceUri = resourceUri;
}
public String getSupportSubscriptionId() {
return supportSubscriptionId;
}
public void setSupportSubscriptionId(String supportSubscriptionId) {
this.supportSubscriptionId = supportSubscriptionId;
}
}
But when trying to deserialise with this func
Type localVarReturnType = new TypeToken<List<InstanceCreatorForAwsMarketplace>>(){}.getType();
ApiResponse<List<InstanceCreatorForAwsMarketplace>> responseFromApiCleint = apiClient.execute(newCall, localVarReturnType);
I get the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Any idea what might be the issue? This looks like a fairly simple json that the rest service returns, but I have not been able to get it work, any help would be greatly appreciated.
Right after I had written the question, I found out the answer, of course the top level class should not be a list, just the class it self. But I have a secondary question, can the three mapper classes be mounted into one class, just a cosmetic issue?
I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();