Getting null from POJO after using JACKSON ObjectMapper - java

I'm struggling whit this problem for a while and can't find a solution.
My intention is to retrieve a POJO from the following JSON using Jackson:
{
"date": "2018-11-27",
"rates": {
"BGN": 1.9558,
"CAD": 1.5018,
"BRL": 4.4011,
"HUF": 324.06,
"DKK": 7.4617,
"JPY": 128.66,
"ILS": 4.2215,
"TRY": 5.9313,
"RON": 4.6583,
"GBP": 0.88748,
"PHP": 59.439,
"HRK": 7.4275,
"NOK": 9.7325,
"USD": 1.1328,
"MXN": 23.1784,
"AUD": 1.5631,
"IDR": 16410.59,
"KRW": 1279.17,
"HKD": 8.8679,
"ZAR": 15.632,
"ISK": 141,
"CZK": 25.914,
"THB": 37.371,
"MYR": 4.7498,
"NZD": 1.6647,
"PLN": 4.2902,
"SEK": 10.2823,
"RUB": 75.6401,
"CNY": 7.8708,
"SGD": 1.5582,
"CHF": 1.1309,
"INR": 80.162
},
"base": "EUR"
}
I solved it with the following code:
public class JsonToPojo {
private static final String URL_LATEST = "https://api.exchangeratesapi.io/latest";
public static String getJson() {
try {
URL url = new URL(URL_LATEST);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
response.append(inputLine);
}
bufferedReader.close();
urlConnection.disconnect();
return response.toString();
} catch (IOException e) {
e.getStackTrace();
return null;
}
}
}
This is my POJO:
public class Currency {
private String date;
private Rates rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Rates getRates() {
return rates;
}
public void setRates(Rates rates) {
this.rates = rates;
}
}
Class using ObjectMapper:
public class CurrencyService {
public static Currency getLatestCurrency(){
try {
ObjectMapper mapper = new ObjectMapper();
Currency currency = mapper.readValue(JsonToPojo.getJson(), Currency.class);
return currency;
}catch (IOException e){
e.getStackTrace();
return null;
}
}
}
When I'm trying to call the get method on my POJO object, I'm getting a NullPointException, so something is wrong with databinding.
my Rates class.
public class Rates {
private float BGN;
private float CAD;
private float BRL;
private float HUF;
private float DKK;
private float JPY;
private float ILS;
private float TRY;
private float RON;
private float GBP;
private float PHP;
private float HRK;
private float NOK;
private float ZAR;
private float MXD;
private float AUD;
private float USD;
private float KRW;
private float HKD;
private float EUR;
private float ISK;
private float CZK;
private float THB;
private float MYR;
private float NZD;
private float PLN;
private float CHF;
private float SEK;
private float CNY;
private float SGD;
private float INR;
private float IDR;
private float RUB;
public void setBGN(Float BGN) {
this.BGN = BGN;
}
public void setCAD(Float CAD) {
this.CAD = CAD;
}
public void setBRL(Float BRL) {
this.BRL = BRL;
}
public void setHUF(Float HUF) {
this.HUF = HUF;
}
public void setDKK(Float DKK) {
this.DKK = DKK;
}
public void setJPY(Float JPY) {
this.JPY = JPY;
}
public void setILS(Float ILS) {
this.ILS = ILS;
}
public void setTRY(Float TRY) {
this.TRY = TRY;
}
public void setRON(Float RON) {
this.RON = RON;
}
public void setGBP(Float GBP) {
this.GBP = GBP;
}
public void setPHP(Float PHP) {
this.PHP = PHP;
}
public void setHRK(Float HRK) {
this.HRK = HRK;
}
public void setNOK(Float NOK) {
this.NOK = NOK;
}
public void setZAR(Float ZAR) {
this.ZAR = ZAR;
}
public void setMXD(Float MXD) {
this.MXD = MXD;
}
public void setAUD(Float AUD) {
this.AUD = AUD;
}
public void setUSD(Float USD) {
this.USD = USD;
}
public void setKRW(Float KRW) {
this.KRW = KRW;
}
public void setHKD(Float HKD) {
this.HKD = HKD;
}
public void setEUR(Float EUR) {
this.EUR = EUR;
}
public void setISK(Float ISK) {
this.ISK = ISK;
}
public void setCZK(Float CZK) {
this.CZK = CZK;
}
public void setTHB(Float THB) {
this.THB = THB;
}
public void setMYR(Float MYR) {
this.MYR = MYR;
}
public void setNZD(Float NZD) {
this.NZD = NZD;
}
public void setPLN(Float PLN) {
this.PLN = PLN;
}
public void setCHF(Float CHF) {
this.CHF = CHF;
}
public void setSEK(Float SEK) {
this.SEK = SEK;
}
public void setCNY(Float CNY) {
this.CNY = CNY;
}
public void setSGD(Float SGD) {
this.SGD = SGD;
}
public void setINR(Float INR) {
this.INR = INR;
}
public void setIDR(Float IDR) {
this.IDR = IDR;
}
public void setRUB(Float RUB) {
this.RUB = RUB;
}
public Float getBGN() {
return BGN;
}
public Float getCAD() {
return CAD;
}
public Float getBRL() {
return BRL;
}
public Float getHUF() {
return HUF;
}
public Float getDKK() {
return DKK;
}
public Float getJPY() {
return JPY;
}
public Float getILS() {
return ILS;
}
public Float getTRY() {
return TRY;
}
public Float getRON() {
return RON;
}
public Float getGBP() {
return GBP;
}
public Float getPHP() {
return PHP;
}
public Float getHRK() {
return HRK;
}
public Float getNOK() {
return NOK;
}
public Float getZAR() {
return ZAR;
}
public Float getMXD() {
return MXD;
}
public Float getAUD() {
return AUD;
}
public Float getUSD() {
return USD;
}
public Float getKRW() {
return KRW;
}
public Float getHKD() {
return HKD;
}
public Float getEUR() {
return EUR;
}
public Float getISK() {
return ISK;
}
public Float getCZK() {
return CZK;
}
public Float getTHB() {
return THB;
}
public Float getMYR() {
return MYR;
}
public Float getNZD() {
return NZD;
}
public Float getPLN() {
return PLN;
}
public Float getCHF() {
return CHF;
}
public Float getSEK() {
return SEK;
}
public Float getCNY() {
return CNY;
}
public Float getSGD() {
return SGD;
}
public Float getINR() {
return INR;
}
public Float getIDR() {
return IDR;
}
public Float getRUB() {
return RUB;
}
}

I've checked your code locally, and have got it working. I didn't have a Rates class, so I used a Map instead (to map the name, with the rate (float)):
import java.util.Map;
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Map<String, Float> getRates() {
return rates;
}
public Float getSingleRate(String rateKey) {
if (rates.containsKey(rateKey)) {
return rates.get(rateKey);
}
return 0.0F;
}
public void setRates(Map<String, Float> rates) {
this.rates = rates;
}
}
I have added the following main() method to your JSonToPojo class:
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Currency currency = new Currency();
String jsonStr = getJson();
try {
currency = mapper.readValue(jsonStr, Currency.class);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
System.out.println(currency.getSingleRate("BGN"));
System.out.println("finished");
}
Running the main() method, produces the following output (I have used [snip] instead of printing out all the JSon (twice)):
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
1.9558
finished
The output for "BGN" is:
1.9558

You can refer to http://www.jsonschema2pojo.org/ to get the correct pojo for your json.
Below is the one I created (moderatley modified)
You can replace like Object date with Date date and so on. If it doesn't work than there is probably some error in your POJO
import com.fasterxml.jackson.annotation.JsonProperty;
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;
public class Example {
#JsonProperty("date")
private Object date;
#JsonProperty("rates")
private Object rates;
#JsonProperty("base")
private Object base;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("date")
public Object getDate() {
return date;
}
#JsonProperty("date")
public void setDate(Object date) {
this.date = date;
}
#JsonProperty("rates")
public Object getRates() {
return rates;
}
#JsonProperty("rates")
public void setRates(Object rates) {
this.rates = rates;
}
#JsonProperty("base")
public Object getBase() {
return base;
}
#JsonProperty("base")
public void setBase(Object base) {
this.base = base;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return "date:" + date.toString() +
",\nrates:" + rates.toString() +
",\nbase: " + base.toString();
}
}
And here is the driver class in which you can read the object and pass in the user defined file path ( i have set it to "test-json.json"). You can update this with your local file path address.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String... args){
Main main = new Main();
Example example = main.readObjectDataFromJsonFile(Example.class,"test-json.json");
System.out.println(example);
}
public <T> T readObjectDataFromJsonFile(Class<T> clazz, String jsonFilePath) {
T populatedObject = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
String objectJson = "";
Stream<String> lines = Files.lines(Paths.get(jsonFilePath));
objectJson = lines.collect(Collectors.joining());
lines.close();
populatedObject = objectMapper.readValue(objectJson, clazz);
} catch (IOException ioException) {
System.out.println("Exception in reading json file");
System.out.println(ioException.getMessage());
}
return populatedObject;
}
}

you can use
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
without any change to your Pojos, but I had to add MXN as a property to Rates class. But ideal way to handle this is having a Map for the rates. Because it can change any time as I understood, either way its easier for access. So change Currency class as follows.
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
// getters and setters
}
access exchange rates as getRates().get('MXN') // returns value.

Related

Spring mvc module not updating values properly.updating as a new row

when I am updating a value in the table that value is added as a new row. not updated current row.I keep going over the code, but I cannot see where the problem is. Can someone show me what to change in the below?
Here are the relevant methods of Webpagecontroller file:
#SuppressWarnings("deprecation")
#RequestMapping(value = "/updateMvPoles",method = RequestMethod.GET, produces = "application/json")
public #ResponseBody void updateMvPoles(#RequestParam("id") String id,#RequestParam("poleno") String poleno,
#RequestParam("polename") String polename,#RequestParam("poletype") String poletype,#RequestParam("poleheight") String poleheight,
#RequestParam("WorkingLoad") String workingload,#RequestParam("pstatus") String pstatus,#RequestParam("gpslatitude") String gpslatitude,#RequestParam("gpslongitude") String gpslongitude,
#RequestParam("kv33conductorcct3") String kv33conductorcct3,#RequestParam("earthdownconductor") String earthdownconductor,#RequestParam("nooflvcct") String nooflvcct,
#RequestParam("kv33conductorcct2") String kv33conductorcct2,#RequestParam("kv33conductorcct1") String kv33conductorcct1,#RequestParam("hvlvcombinerun") String hvlvcombinerun,
#RequestParam("kv11conductorcct2") String kv11conductorcct2,#RequestParam("kv11conductorcct1") String kv11conductorcct1,#RequestParam("kv11conductorcct3") String kv11conductorcct3,
#RequestParam("streetlight") String streetlight,#RequestParam("noof33kvcircuits") String noof33kvcircuits,#RequestParam("noof11kvcircuits") String noof11kvcircuits,
#RequestParam("lvconductortype") String lvconductortype,#RequestParam("crossarm") String crossarm)
{
//provinceDao.updateProvince(province,id,status);
try{
System.out.println("hiiiiii66666");
MmsAddmvpole obj = new MmsAddmvpole();
obj = mvPoleDao.findById(Long.valueOf(id));
obj.setId(new Long(id));
obj.setPoleNo(poleno);
obj.setPoleName(polename);
obj.setPoleType(new BigDecimal(poletype));
obj.setPoleHeight(new BigDecimal(poleheight));
obj.setWorkingLoad(new BigDecimal(workingload));
obj.setStatus(new BigDecimal(pstatus));
obj.setGpsLatitude(new BigDecimal(gpslatitude));
obj.setGpsLongitude(new BigDecimal(gpslongitude));
obj.setKv33ConductorCct3(new BigDecimal(kv33conductorcct3));
obj.setEarthConductor(new BigDecimal(earthdownconductor));
obj.setNoOfLvCct(new BigDecimal(nooflvcct));
obj.setKv33ConductorCct2(new BigDecimal(kv33conductorcct2));
obj.setKv33ConductorCct1(new BigDecimal(kv33conductorcct1));
obj.setHvLvCombineRun(new BigDecimal(hvlvcombinerun));
obj.setKv11ConductorCct2(new BigDecimal(kv11conductorcct2));
obj.setKv11ConductorCct1(new BigDecimal(kv11conductorcct1));
obj.setKv11ConductorCct3(new BigDecimal(kv11conductorcct3));
obj.setStreetLight(new BigDecimal(streetlight));
obj.setNoOf33Kvcircuits(new BigDecimal(noof33kvcircuits));
obj.setNoOf11Kvcircuits(new BigDecimal(noof11kvcircuits));
obj.setLvConductorType(new BigDecimal(lvconductortype));
obj.setCrossArm(new BigDecimal(crossarm));
mvPoleDao.update(obj);
}catch(Exception e){
}
}
Here is function for update button in editMVPoleNew.jsp
function saveAll() {
//alert('hiiiii');
var len = arrayDataToSave.length
for (var count = 0; count < len; count++) {
var pid = arrayDataToSave[count];
var poleNo = document.getElementById("poleNo_" + pid).value;
var poleName = document.getElementById("poleName_" + pid).value;
var poleType = document.getElementById("poleType_" + pid).value;
var poleHeight = document.getElementById("poleHeight_" + pid).value;
var workingLoad = document.getElementById("workingLoad_" + pid).value;
var pstatus = document.getElementById("pstatus_" + pid).value;
var gps_latitude= document.getElementById("gps_latitude_"+ pid).value;
var gps_longitude = document.getElementById("gps_longitude_" + pid).value;
var kV33Conductorcct_3= document.getElementById("kV33Conductorcct_3_" + pid).value
var EarthDownconductor = document.getElementById("EarthDownconductor_" + pid).value
var NoofLVcct=document.getElementById("NoofLVcct_" + pid).value
var kV33Conductorcct_2=document.getElementById("kV33Conductorcct_2_" + pid).value
var kV33Conductorcct_1=document.getElementById("kV33Conductorcct_1_" + pid).value
var HVLVCombineRun=document.getElementById("HVLVCombineRun_" + pid).value
var kV11Conductorcct_2=document.getElementById("kV11Conductorcct_2_"+ pid).value
var kV11Conductorcct_1=document.getElementById("kV11Conductorcct_1_" +pid). value
var kV11Conductorcct_3=document.getElementById("kV11Conductorcct_3_"+ pid).value
var StreetLight=document.getElementById("StreetLight_"+ pid).value
var Noof33kVCircuits=document.getElementById("Noof33kVCircuits_"+ pid).value
var Noof11kVCircuits=document.getElementById("Noof11kVCircuits_" + pid).value
var LVConductortype=document.getElementById("LVConductortype_"+ pid).value
var CrossArm=document.getElementById("CrossArm_" + pid).value
var url = "/MMS/updateMvPoles?id=" +pid+ "&poleno=" +poleNo+ "&polename=" +poleName+ "&poletype=" +poleType+
"&poleheight=" +poleHeight+ "&WorkingLoad=" +workingLoad+ "&pstatus=" +pstatus+ "&gpslatitude=" +gps_latitude+
"&gpslongitude=" +gps_longitude+ "&kv33conductorcct3=" +kV33Conductorcct_3+ "&earthdownconductor=" +EarthDownconductor+
"&nooflvcct=" +NoofLVcct+ "&kv33conductorcct2=" +kV33Conductorcct_2+ "&kv33conductorcct1=" +kV33Conductorcct_1+ "&hvlvcombinerun=" +HVLVCombineRun+
"&kv11conductorcct2=" +kV11Conductorcct_2+ "&kv11conductorcct1=" +kV11Conductorcct_1+ "&kv11conductorcct3=" +kV11Conductorcct_3+ "&streetlight=" +StreetLight+
"&noof33kvcircuits=" +Noof33kVCircuits+ "&noof11kvcircuits=" +Noof11kVCircuits+ "&lvconductortype=" +LVConductortype+ "&crossarm=" +CrossArm;
// alert('hiiiii' +url);
$.ajax({
type : "GET",
url : url,
success : function(response) {
//alert("Line updated succesfully...");
console.log(response);
window.location.reload();
disable(pid);
}
});
}
alert("Lines updated succesfully... ");
}
Here is MmsAddmvPole.java
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqGen")
#SequenceGenerator(name = "SeqGen", sequenceName = "POLEMV_SEQ", allocationSize = 1)
private long id;
private String area;
#Column(name="CROSS_ARM")
private BigDecimal crossArm;
#Column(name="EARTH_CONDUCTOR")
private BigDecimal earthConductor;
#Column(name="GPS_LATITUDE")
private BigDecimal gpsLatitude;
#Column(name="GPS_LONGITUDE")
private BigDecimal gpsLongitude;
#Column(name="HV_LV_COMBINE_RUN")
private BigDecimal hvLvCombineRun;
#Column(name="KV11_CONDUCTOR_CCT_2")
private BigDecimal kv11ConductorCct2;
#Column(name="KV11_CONDUCTOR_CCT_1")
private BigDecimal kv11ConductorCct1;
#Column(name="KV11_CONDUCTOR_CCT_3")
private BigDecimal kv11ConductorCct3;
#Column(name="KV33_CCT_1_PH_1")
private BigDecimal kv33Cct1Ph1;
#Column(name="KV33_CCT_1_PH_2")
private BigDecimal kv33Cct1Ph2;
#Column(name="KV33_CCT_1_PH_3")
private BigDecimal kv33Cct1Ph3;
#Column(name="KV33_CCT_2_PH_1")
private BigDecimal kv33Cct2Ph1;
#Column(name="KV33_CCT_2_PH_2")
private BigDecimal kv33Cct2Ph2;
#Column(name="KV33_CCT_2_PH_3")
private BigDecimal kv33Cct2Ph3;
#Column(name="KV33_CCT_3_PH_1")
private BigDecimal kv33Cct3Ph1;
#Column(name="KV33_CCT_3_PH_2")
private BigDecimal kv33Cct3Ph2;
#Column(name="KV33_CCT_3_PH_3")
private BigDecimal kv33Cct3Ph3;
#Column(name="KV33_CONDUCTOR_CCT_1")
private BigDecimal kv33ConductorCct1;
#Column(name="KV33_CONDUCTOR_CCT_2")
private BigDecimal kv33ConductorCct2;
#Column(name="KV33_CONDUCTOR_CCT_3")
private BigDecimal kv33ConductorCct3;
#Column(name="LINE_END")
private BigDecimal lineEnd;
#Column(name="LV_CONDUCTOR_TYPE")
private BigDecimal lvConductorType;
#Column(name="MV_SWITCH")
private BigDecimal mvSwitch;
#Column(name="NO_OF_11_KVCIRCUITS")
private BigDecimal noOf11Kvcircuits;
#Column(name="NO_OF_33_KVCIRCUITS")
private BigDecimal noOf33Kvcircuits;
#Column(name="NO_OF_LV_CCT")
private BigDecimal noOfLvCct;
#Column(name="NO_OF_CCT")
private BigDecimal noOfCct;
public BigDecimal getNoOfCct() {
return noOfCct;
}
public void setNoOfCct(BigDecimal noOfCct) {
this.noOfCct = noOfCct;
}
#Column(name="PIN_SHACKLE")
private BigDecimal pinShackle;
#Column(name="POLE_HEIGHT")
private BigDecimal poleHeight;
#Column(name="POLE_NAME")
private String poleName;
#Column(name="POLE_NO")
private String poleNo;
#Column(name="POLE_TYPE")
private BigDecimal poleType;
private BigDecimal status;
private BigDecimal stay;
#Column(name="STREET_LIGHT")
private BigDecimal streetLight;
#Column(name="TRANSFORMER_CAPACITY")
private BigDecimal transformerCapacity;
#Column(name="TRANSFORMER_TYPE")
private BigDecimal transformerType;
#Column(name="WORKING_LOAD")
private BigDecimal workingLoad;
private BigDecimal strut;
#Column(name="STRUT_HEIGHT")
private BigDecimal strutHeight;
public BigDecimal getStrutHeight() {
return strutHeight;
}
public void setStrutHeight(BigDecimal strutHeight) {
this.strutHeight = strutHeight;
}
#Column(name="STRUT_TYPE")
private BigDecimal strutType;
public BigDecimal getStrutType() {
return strutType;
}
public void setStrutType(BigDecimal strutType) {
this.strutType = strutType;
}
#Column(name="STRUT_WORKING_LOAD")
private BigDecimal strutWorkingLoad;
public BigDecimal getStrutWorkingLoad() {
return strutWorkingLoad;
}
public void setStrutWorkingLoad(BigDecimal strutWorkingLoad) {
this.strutWorkingLoad = strutWorkingLoad;
}
#Column(name="STAY_TYPE")
private BigDecimal stayType;
public BigDecimal getStayType() {
return stayType;
}
public void setStayType(BigDecimal stayType) {
this.stayType = stayType;
}
public MmsAddmvpole() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
public BigDecimal getCrossArm() {
return this.crossArm;
}
public void setCrossArm(BigDecimal crossArm) {
this.crossArm = crossArm;
}
public BigDecimal getEarthConductor() {
return this.earthConductor;
}
public void setEarthConductor(BigDecimal earthConductor) {
this.earthConductor = earthConductor;
}
public BigDecimal getGpsLatitude() {
return this.gpsLatitude;
}
public void setGpsLatitude(BigDecimal gpsLatitude) {
this.gpsLatitude = gpsLatitude;
}
public BigDecimal getGpsLongitude() {
return this.gpsLongitude;
}
public void setGpsLongitude(BigDecimal gpsLongitude) {
this.gpsLongitude = gpsLongitude;
}
public BigDecimal getHvLvCombineRun() {
return this.hvLvCombineRun;
}
public void setHvLvCombineRun(BigDecimal hvLvCombineRun) {
this.hvLvCombineRun = hvLvCombineRun;
}
public BigDecimal getKv11ConductorCct1() {
return this.kv11ConductorCct1;
}
public void setKv11ConductorCct1(BigDecimal kv11ConductorCct1) {
this.kv11ConductorCct1 = kv11ConductorCct1;
}
public BigDecimal getKv11ConductorCct2() {
return this.kv11ConductorCct2;
}
public void setKv11ConductorCct2(BigDecimal kv11ConductorCct2) {
this.kv11ConductorCct2 = kv11ConductorCct2;
}
public BigDecimal getKv11ConductorCct3() {
return this.kv11ConductorCct3;
}
public void setKv11ConductorCct3(BigDecimal kv11ConductorCct3) {
this.kv11ConductorCct3 = kv11ConductorCct3;
}
public BigDecimal getKv33Cct1Ph1() {
return this.kv33Cct1Ph1;
}
public void setKv33Cct1Ph1(BigDecimal kv33Cct1Ph1) {
this.kv33Cct1Ph1 = kv33Cct1Ph1;
}
public BigDecimal getKv33Cct1Ph2() {
return this.kv33Cct1Ph2;
}
public void setKv33Cct1Ph2(BigDecimal kv33Cct1Ph2) {
this.kv33Cct1Ph2 = kv33Cct1Ph2;
}
public BigDecimal getKv33Cct1Ph3() {
return this.kv33Cct1Ph3;
}
public void setKv33Cct1Ph3(BigDecimal kv33Cct1Ph3) {
this.kv33Cct1Ph3 = kv33Cct1Ph3;
}
public BigDecimal getKv33Cct2Ph1() {
return this.kv33Cct2Ph1;
}
public void setKv33Cct2Ph1(BigDecimal kv33Cct2Ph1) {
this.kv33Cct2Ph1 = kv33Cct2Ph1;
}
public BigDecimal getKv33Cct2Ph2() {
return this.kv33Cct2Ph2;
}
public void setKv33Cct2Ph2(BigDecimal kv33Cct2Ph2) {
this.kv33Cct2Ph2 = kv33Cct2Ph2;
}
public BigDecimal getKv33Cct2Ph3() {
return this.kv33Cct2Ph3;
}
public void setKv33Cct2Ph3(BigDecimal kv33Cct2Ph3) {
this.kv33Cct2Ph3 = kv33Cct2Ph3;
}
public BigDecimal getKv33Cct3Ph1() {
return this.kv33Cct3Ph1;
}
public void setKv33Cct3Ph1(BigDecimal kv33Cct3Ph1) {
this.kv33Cct3Ph1 = kv33Cct3Ph1;
}
public BigDecimal getKv33Cct3Ph2() {
return this.kv33Cct3Ph2;
}
public void setKv33Cct3Ph2(BigDecimal kv33Cct3Ph2) {
this.kv33Cct3Ph2 = kv33Cct3Ph2;
}
public BigDecimal getKv33Cct3Ph3() {
return this.kv33Cct3Ph3;
}
public void setKv33Cct3Ph3(BigDecimal kv33Cct3Ph3) {
this.kv33Cct3Ph3 = kv33Cct3Ph3;
}
public BigDecimal getKv33ConductorCct1() {
return this.kv33ConductorCct1;
}
public void setKv33ConductorCct1(BigDecimal kv33ConductorCct1) {
this.kv33ConductorCct1 = kv33ConductorCct1;
}
public BigDecimal getKv33ConductorCct2() {
return this.kv33ConductorCct2;
}
public void setKv33ConductorCct2(BigDecimal kv33ConductorCct2) {
this.kv33ConductorCct2 = kv33ConductorCct2;
}
public BigDecimal getKv33ConductorCct3() {
return this.kv33ConductorCct3;
}
public void setKv33ConductorCct3(BigDecimal kv33ConductorCct3) {
this.kv33ConductorCct3 = kv33ConductorCct3;
}
public BigDecimal getLineEnd() {
return this.lineEnd;
}
public void setLineEnd(BigDecimal lineEnd) {
this.lineEnd = lineEnd;
}
public BigDecimal getLvConductorType() {
return this.lvConductorType;
}
public void setLvConductorType(BigDecimal lvConductorType) {
this.lvConductorType = lvConductorType;
}
public BigDecimal getMvSwitch() {
return this.mvSwitch;
}
public void setMvSwitch(BigDecimal mvSwitch) {
this.mvSwitch = mvSwitch;
}
public BigDecimal getNoOf11Kvcircuits() {
return this.noOf11Kvcircuits;
}
public void setNoOf11Kvcircuits(BigDecimal noOf11Kvcircuits) {
this.noOf11Kvcircuits = noOf11Kvcircuits;
}
public BigDecimal getNoOf33Kvcircuits() {
return this.noOf33Kvcircuits;
}
public void setNoOf33Kvcircuits(BigDecimal noOf33Kvcircuits) {
this.noOf33Kvcircuits = noOf33Kvcircuits;
}
public BigDecimal getNoOfLvCct() {
return this.noOfLvCct;
}
public void setNoOfLvCct(BigDecimal noOfLvCct) {
this.noOfLvCct = noOfLvCct;
}
public BigDecimal getPinShackle() {
return this.pinShackle;
}
public void setPinShackle(BigDecimal pinShackle) {
this.pinShackle = pinShackle;
}
public BigDecimal getPoleHeight() {
return this.poleHeight;
}
public void setPoleHeight(BigDecimal poleHeight) {
this.poleHeight = poleHeight;
}
public String getPoleName() {
return this.poleName;
}
public void setPoleName(String poleName) {
this.poleName = poleName;
}
public String getPoleNo() {
return this.poleNo;
}
public void setPoleNo(String poleNo) {
this.poleNo = poleNo;
}
public BigDecimal getPoleType() {
return this.poleType;
}
public void setPoleType(BigDecimal poleType) {
this.poleType = poleType;
}
public BigDecimal getStatus() {
return this.status;
}
public void setStatus(BigDecimal status) {
this.status = status;}
public BigDecimal getStay() {
return this.stay;
}
public void setStay(BigDecimal stay) {
this.stay = stay;
}
public BigDecimal getStreetLight() {
return this.streetLight;
}
public void setStreetLight(BigDecimal streetLight) {
this.streetLight = streetLight;
}
public BigDecimal getStrut() {
return this.strut;
}
public void setStrut(BigDecimal strut) {
this.strut = strut;
}
public BigDecimal getTransformerCapacity() {
return this.transformerCapacity;
}
public void setTransformerCapacity(BigDecimal transformerCapacity) {
this.transformerCapacity = transformerCapacity;
}
public BigDecimal getTransformerType() {
return this.transformerType;
}
public void setTransformerType(BigDecimal transformerType) {
this.transformerType = transformerType;
}
public BigDecimal getWorkingLoad() {
return this.workingLoad;
}
public void setWorkingLoad(BigDecimal workingLoad) {
this.workingLoad = workingLoad;
}

Can't get all data from my model class using Retrofit

I need a little help, I'd already run out of ideas, tried to run this program out for two days, but I'm literally out of any ideas. So, I want from program to:
Display actual currency exchange
In another activity, the program should have a possibility to calculate currencies (let's say, we have a String with value "CZK" so the program should get from Model class currency value, to get that possibility to calculate the currencies, and here's the problem, I can't get those values. Actually, I can display it, but I want to call methods like getCZK(); because there are the actual values of those currencies. To be more accurate, ill try to explain it in other way: Let's say, the base currency is EUR, user selected option, that he want converse EUR to CZK, so program should have a String based of user choice (in this case it's String with value "CZK") now, program should search in switch case for value such as CZK, when it will find it, it should pass method like getCZK(); to suitable variable, to make conversion possible. I hope I explained it well to you guys.
Model class
public class Model {
#SerializedName("base")
private String base;
#SerializedName("rates")
private Map<String, Double> rates;
public void setRates(Map<String, Double> rates) {
this.rates = rates;
}
public void setBase(String base) {
this.base = base;
}
public String getBase() {
return base;
}
public Map<String, Double> getRates() {
return rates;
}
class Rates {
#SerializedName("BGN")
private Double bGN;
#SerializedName("NZD")
private Double nZD;
#SerializedName("ILS")
private Double iLS;
#SerializedName("RUB")
private Double rUB;
#SerializedName("CAD")
private Double cAD;
#SerializedName("USD")
private Double uSD;
#SerializedName("PHP")
private Double pHP;
#SerializedName("CHF")
private Double cHF;
#SerializedName("ZAR")
private Double zAR;
#SerializedName("AUD")
private Double aUD;
#SerializedName("JPY")
private Double jPY;
#SerializedName("TRY")
private Double tRY;
#SerializedName("HKD")
private Double hKD;
#SerializedName("MYR")
private Double mYR;
#SerializedName("THB")
private Double tHB;
#SerializedName("HRK")
private Double hRK;
#SerializedName("NOK")
private Double nOK;
#SerializedName("IDR")
private Double iDR;
#SerializedName("DKK")
private Double dKK;
#SerializedName("CZK")
private Double cZK;
#SerializedName("HUF")
private Double hUF;
#SerializedName("GBP")
private Double gBP;
#SerializedName("MXN")
private Double mXN;
#SerializedName("KRW")
private Double kRW;
#SerializedName("ISK")
private Double iSK;
#SerializedName("SGD")
private Double sGD;
#SerializedName("BRL")
private Double bRL;
#SerializedName("PLN")
private Double pLN;
#SerializedName("INR")
private Double iNR;
#SerializedName("RON")
private Double rON;
#SerializedName("CNY")
private Double cNY;
#SerializedName("SEK")
private Double sEK;
public Double getBGN() {
return bGN;
}
public void setBGN(Double value) {
this.bGN = value;
}
public Double getNZD() {
return nZD;
}
public void setNZD(Double value) {
this.nZD = value;
}
public Double getILS() {
return iLS;
}
public void setILS(Double value) {
this.iLS = value;
}
public Double getRUB() {
return rUB;
}
public void setRUB(Double value) {
this.rUB = value;
}
public Double getCAD() {
return cAD;
}
public void setCAD(Double value) {
this.cAD = value;
}
public Double getUSD() {
return uSD;
}
public void setUSD(Double value) {
this.uSD = value;
}
public Double getPHP() {
return pHP;
}
public void setPHP(Double value) {
this.pHP = value;
}
public Double getCHF() {
return cHF;
}
public void setCHF(Double value) {
this.cHF = value;
}
public Double getZAR() {
return zAR;
}
public void setZAR(Double value) {
this.zAR = value;
}
public Double getAUD() {
return aUD;
}
public void setAUD(Double value) {
this.aUD = value;
}
public Double getJPY() {
return jPY;
}
public void setJPY(Double value) {
this.jPY = value;
}
public Double getTRY() {
return tRY;
}
public void setTRY(Double value) {
this.tRY = value;
}
public Double getHKD() {
return hKD;
}
public void setHKD(Double value) {
this.hKD = value;
}
public Double getMYR() {
return mYR;
}
public void setMYR(Double value) {
this.mYR = value;
}
public Double getTHB() {
return tHB;
}
public void setTHB(Double value) {
this.tHB = value;
}
public Double getHRK() {
return hRK;
}
public void setHRK(Double value) {
this.hRK = value;
}
public Double getNOK() {
return nOK;
}
public void setNOK(Double value) {
this.nOK = value;
}
public Double getIDR() {
return iDR;
}
public void setIDR(Double value) {
this.iDR = value;
}
public Double getDKK() {
return dKK;
}
public void setDKK(Double value) {
this.dKK = value;
}
public Double getCZK() {
return cZK;
}
public void setCZK(Double value) {
this.cZK = value;
}
public Double getHUF() {
return hUF;
}
public void setHUF(Double value) {
this.hUF = value;
}
public Double getGBP() {
return gBP;
}
public void setGBP(Double value) {
this.gBP = value;
}
public Double getMXN() {
return mXN;
}
public void setMXN(Double value) {
this.mXN = value;
}
public Double getKRW() {
return kRW;
}
public void setKRW(Double value) {
this.kRW = value;
}
public Double getISK() {
return iSK;
}
public void setISK(Double value) {
this.iSK = value;
}
public Double getSGD() {
return sGD;
}
public void setSGD(Double value) {
this.sGD = value;
}
public Double getBRL() {
return bRL;
}
public void setBRL(Double value) {
this.bRL = value;
}
public Double getPLN() {
return pLN;
}
public void setPLN(Double value) {
this.pLN = value;
}
public Double getINR() {
return iNR;
}
public void setINR(Double value) {
this.iNR = value;
}
public Double getRON() {
return rON;
}
public void setRON(Double value) {
this.rON = value;
}
public Double getCNY() {
return cNY;
}
public void setCNY(Double value) {
this.cNY = value;
}
public Double getSEK() {
return sEK;
}
public void setSEK(Double value) {
this.sEK = value;
}
}
Api
public interface Api {
#GET("latest")
Call<Model> getRates();
#GET("latest")
Call<Model> getRatesByGivenCurrency(#Query("base") String base);
}
Java class
public class exchange_currency extends AppCompatActivity {
Api api;
TextView currentCurrency, fromTV, toTV, receivedValue;
EditText enteredValue;
Spinner spinner;
Button button;
List<Model> list;
String keyString;
double valueDouble;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_currency);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.exchangeratesapi.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
spinner = (Spinner) findViewById(R.id.currencyNationalitiesSpinner);
button = (Button) findViewById(R.id.btn);
currentCurrency = (TextView) findViewById(R.id.currentValue);
fromTV = (TextView) findViewById(R.id.actualCurrency);
toTV = (TextView) findViewById(R.id.wantedCurrency);
receivedValue = (TextView) findViewById(R.id.receivedValue);
enteredValue = (EditText) findViewById(R.id.actualET);
api = retrofit.create(Api.class);
createRetrofit();
}
public void createRetrofit() {
Call<Model> call = api.getRates();
call.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (!response.isSuccessful()) {
Toast.makeText(exchange_currency.this, response.code(), Toast.LENGTH_LONG).show();
}
list = Collections.singletonList(response.body());
for (Model model : list) {
Iterator<Map.Entry<String, Double>> entries = model.getRates().entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
keyString = (String) entry.getKey();
valueDouble = (Double) entry.getValue();
toTV.append(keyString + "\n");
receivedValue.append(String.valueOf(valueDouble) + "\n");
toTV.append((CharSequence) model.getRates());
}
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(exchange_currency.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Api that I using https://exchangeratesapi.io/
exemplary GET response from API
{"base":"EUR","rates":{"BGN":1.9558,"NZD":1.7056,"ILS":4.0147,"RUB":73.2104,"CAD":1.5117,"USD":1.1226,"PHP":58.898,"CHF":1.1307,"ZAR":15.9746,"AUD":1.6162,"JPY":123.0,"TRY":6.7732,"HKD":8.8112,"MYR":4.6818,"THB":35.362,"HRK":7.4113,"NOK":9.799,"IDR":16199.12,"DKK":7.4691,"CZK":25.751,"HUF":324.23,"GBP":0.86723,"MXN":21.5178,"KRW":1333.2,"ISK":137.8,"SGD":1.5366,"BRL":4.4743,"PLN":4.3061,"INR":79.0375,"RON":4.7615,"CNY":7.7252,"SEK":10.779},"date":"2019-05-14"}
these lines here
#SerializedName("rates")
private Map<String, Double> rates;
Should instead be like this
#SerializedName("rates")
private Rates rates;
Then in the onResponse you can get each of the values from the response like
Log.d("check", "CAD: "+response.body().getRates().getCAD());
Log.d("check", "GBP: "+response.body().getRates().getGBP());
Which returns
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: CAD: 1.5117
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: GBP: 0.86723
Does this answer your question?

How can I set My Json Value in Adapter

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

List of class objects from list of strings

I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);

How to pass array of string in insert query in ibatis?

How to pass array of string in insert query statement in ibatis. On passing string array as parameter it is giving me this exception of ibatis -
Can't infer the SQL type to use for an instance of [Ljava.lang.String;. Use setObject() with an explicit Types value to specify the type to use.
How to solve this error ?
My method is -
public void insertCampaignData(String campaignData, ObjectMapper jsonObjMapper) {
Campaign campaign = null;
SqlSession session = null;
IfrmCreateCampaign createCampaign = null;
try {
campaign = jsonObjMapper.readValue(campaignData,Campaign.class);
session = DBConnectionFactory.getNewSession();
createCampaign = session.getMapper(IfrmCreateCampaign.class);
createCampaign.insertCampaignData(campaign);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
My entity class is -
import java.io.File;
import java.util.Date;
public class Campaign {
private long campaignId;
private String campaignName;
private long keywordId;
private String brandName;
private String clientName;
private String mobileNum;
private Date startTime;
private Date endTime;
private double campaignBudget;
private double allocatedFund;
private double campaignRate;
private boolean basicTgt;
private boolean customTgt;
private boolean advTgt;
private boolean chechme;
private boolean couponSend;
private String couponFrom;
private String couponTo;
private String couponFilePath;
private File[] couponFile;
private String[] couponFileFileName;
private String[] couponFileContent;
private String callbackUrl;
private String status;
private int campaignTypeId;
private long roAmount;
// edit
private int roType;
public int getRoType() {
return roType;
}
public void setRoType(int roType) {
this.roType = roType;
}
// edit
private String strStartTime;
private String strEndTime;
private String keyword;
private String keywordNum;
private int goal;
private double spentAmount;
private int goalAchievePercent;
private int dial;
private int uniqueDial;
private long userId;
private double campaignTotalAmount;
private double operatorShare;
private long responseCount;
private String strRoPdfFileName;
private File[] roPdf;
private String[] roPdfFileName;
private String[] roPdfContent;
public long getCampaignId() {
return campaignId;
}
public void setCampaignId(long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public long getKeywordId() {
return keywordId;
}
public void setKeywordId(long keywordId) {
this.keywordId = keywordId;
}
public String getKeywordNum() {
return keywordNum;
}
public void setKeywordNum(String keywordNum) {
this.keywordNum = keywordNum;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getMobileNum() {
return mobileNum;
}
public void setMobileNum(String mobileNum) {
this.mobileNum = mobileNum;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public double getCampaignBudget() {
return campaignBudget;
}
public void setCampaignBudget(double campaignBudget) {
this.campaignBudget = campaignBudget;
}
public double getAllocatedFund() {
return allocatedFund;
}
public void setAllocatedFund(double allocatedFund) {
this.allocatedFund = allocatedFund;
}
public double getCampaignRate() {
return campaignRate;
}
public void setCampaignRate(double campaignRate) {
this.campaignRate = campaignRate;
}
public boolean isBasicTgt() {
return basicTgt;
}
public void setBasicTgt(boolean basicTgt) {
this.basicTgt = basicTgt;
}
public boolean isCustomTgt() {
return customTgt;
}
public void setCustomTgt(boolean customTgt) {
this.customTgt = customTgt;
}
public boolean isAdvTgt() {
return advTgt;
}
public void setAdvTgt(boolean advTgt) {
this.advTgt = advTgt;
}
public boolean isChechme() {
return chechme;
}
public void setChechme(boolean chechme) {
this.chechme = chechme;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStrStartTime() {
return strStartTime;
}
public void setStrStartTime(String strStartTime) {
this.strStartTime = strStartTime;
}
public String getStrEndTime() {
return strEndTime;
}
public void setStrEndTime(String strEndTime) {
this.strEndTime = strEndTime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
public double getSpentAmount() {
return spentAmount;
}
public void setSpentAmount(double spentAmount) {
this.spentAmount = spentAmount;
}
public int getGoalAchievePercent() {
return goalAchievePercent;
}
public void setGoalAchievePercent(int goalAchievePercent) {
this.goalAchievePercent = goalAchievePercent;
}
public int getDial() {
return dial;
}
public void setDial(int dial) {
this.dial = dial;
}
public int getUniqueDial() {
return uniqueDial;
}
public void setUniqueDial(int uniqueDial) {
this.uniqueDial = uniqueDial;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isCouponSend() {
return couponSend;
}
public void setCouponSend(boolean couponSend) {
this.couponSend = couponSend;
}
public String getCouponFrom() {
return couponFrom;
}
public void setCouponFrom(String couponFrom) {
this.couponFrom = couponFrom;
}
public String getCouponTo() {
return couponTo;
}
public void setCouponTo(String couponTo) {
this.couponTo = couponTo;
}
public String getCouponFilePath() {
return couponFilePath;
}
public void setCouponFilePath(String couponFilePath) {
this.couponFilePath = couponFilePath;
}
public File[] getCouponFile() {
return couponFile;
}
public void setCouponFile(File[] couponFile) {
this.couponFile = couponFile;
}
public String[] getCouponFileFileName() {
return couponFileFileName;
}
public void setCouponFileFileName(String[] couponFileFileName) {
this.couponFileFileName = couponFileFileName;
}
public String[] getCouponFileContent() {
return couponFileContent;
}
public void setCouponFileContent(String[] couponFileContent) {
this.couponFileContent = couponFileContent;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public int getCampaignTypeId() {
return campaignTypeId;
}
public void setCampaignTypeId(int campaignTypeId) {
this.campaignTypeId = campaignTypeId;
}
public long getRoAmount() {
return roAmount;
}
public void setRoAmount(long roAmount) {
this.roAmount = roAmount;
}
public double getOperatorShare() {
return operatorShare;
}
public void setOperatorShare(double operatorShare) {
this.operatorShare = operatorShare;
}
public long getResponseCount() {
return responseCount;
}
public void setResponseCount(long responseCount) {
this.responseCount = responseCount;
}
public double getCampaignTotalAmount() {
return campaignTotalAmount;
}
public void setCampaignTotalAmount(double campaignTotalAmount) {
this.campaignTotalAmount = campaignTotalAmount;
}
public String getStrRoPdfFileName() {
return strRoPdfFileName;
}
public void setStrRoPdfFileName(String strRoPdfFileName) {
this.strRoPdfFileName = strRoPdfFileName;
}
public File[] getRoPdf() {
return roPdf;
}
public void setRoPdf(File[] roPdf) {
this.roPdf = roPdf;
}
public String[] getRoPdfFileName() {
return roPdfFileName;
}
public void setRoPdfFileName(String[] roPdfFileName) {
this.roPdfFileName = roPdfFileName;
}
public String[] getRoPdfContent() {
return roPdfContent;
}
public void setRoPdfContent(String[] roPdfContent) {
this.roPdfContent = roPdfContent;
}
}
My xml mapping file is -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mogae.starStarWebServices.db.dao.IfrmCreateCampaign">
<insert id="insertCampaignData" statementType="PREPARED" >
insert into campaign(campaign_id,campaign_name,keyword_id,brand_name,client_name,mobile_num,start_time,end_time,campaign_type_id,ro_amount,ro_type,ro_pdf_file_name,campaign_budget,allocated_fund,campaign_rate,is_basic_tgt,is_custom_tgt,is_adv_tgt,is_checkme,is_coupon_send,coupon_from,coupon_to,coupon_file,callback_url,status) values (#{campaignId},#{campaignName},#{keywordId},#{brandName},#{clientName},#{mobileNum},#{startTime},#{endTime},#{campaignTypeId},#{roAmount},#{roType},
#{strRoPdfFileName},#{campaignBudget},#{allocatedFund},#{campaignRate},#{basicTgt},#{customTgt},#{advTgt},#{chechme},#{couponSend},#{couponFrom},#{couponTo},#{couponFileFileName},#{callbackUrl},#{status});
</insert>
<insert id="insertKeywordData" statementType="PREPARED" >
insert into keywords(keyword_id,keyword,keyword_num,booked_by,purchased_on,expires_on,status) values (#{keywordId},#{keyword},#{keywordNum},#{bookedBy},#{purchasedOn},#{expiresOn},#{status})
</insert>
</mapper>

Categories

Resources