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
Related
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.
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();
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);
}
}
I have created Spring MVC 4 with MyBatis. I am very sure I am all set up correctly. For Some reason I am getting this error. Any help is appreciated
Apr 30, 2015 7:22:56 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [myBatisServlet] in context with path [/APMS] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'one' not found. Available parameters are [0, 1, 2, param5, 3, 4, param3, param4, param1, param2]] with root cause
org.apache.ibatis.binding.BindingException: Parameter 'one' not found. Available parameters are [0, 1, 2, param5, 3, 4, param3, param4, param1, param2]
at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:165)
at org.apache.ibatis.reflection.wrapper.MapWrapper.get(MapWrapper.java:44)
at org.apache.ibatis.reflection.MetaObject.getValue(MetaObject.java:116)
at org.apache.ibatis.executor.BaseExecutor.createCacheKey(BaseExecutor.java:186)
at org.apache.ibatis.executor.CachingExecutor.createCacheKey(CachingExecutor.java:129)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:76)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:108)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358)
at com.sun.proxy.$Proxy17.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy30.getResult(Unknown Source)
at com.gm.app.apms.service.WbbCodeService.getTableResult(WbbCodeService.java:24)
at com.gm.app.apms.controller.WbbOrderStatusController.getAllOrdersResults(WbbOrderStatusController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Controller class
package com.gm.app.apms.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.gm.app.apms.model.WbbOrderStatusForm;
import com.gm.app.apms.model.WbbOrderStatusResult;
import com.gm.app.apms.service.IWbbCodeService;
#Controller
#SessionAttributes("wbborderstatusform")
public class WbbOrderStatusController {
#Autowired
private IWbbCodeService iWbbCodeService;
#RequestMapping(value="/viewallorders", method=RequestMethod.POST)
public ModelAndView getAllOrdersResults (#ModelAttribute("wbbOrderStatusForm") WbbOrderStatusForm wbbOrderStatusForm) throws Exception
{
System.out.println(" I AM HERE");
String DateFrom = wbbOrderStatusForm.getDateFrom();
String DateTo = wbbOrderStatusForm.getDateTo();
String orderType = wbbOrderStatusForm.getOrderType();
String distCode = wbbOrderStatusForm.getDistCode();
String packingCode = wbbOrderStatusForm.getPackingCode();
System.out.println("DateFrom "+DateFrom);
System.out.println("DateTo "+DateTo);
System.out.println("orderType "+orderType);
System.out.println("distCode "+distCode);
System.out.println("packingCode "+packingCode);
ModelAndView showresult = new ModelAndView("showresults");
List <WbbOrderStatusResult> tablelist = new ArrayList<WbbOrderStatusResult>();
if (!DateFrom.isEmpty() && !DateTo.isEmpty() && !orderType.isEmpty() && !distCode.isEmpty() && !packingCode.isEmpty()){
tablelist = iWbbCodeService.getTableResult(DateFrom, DateTo, orderType, distCode, packingCode);
showresult.addObject("tablelist", tablelist);
}
return showresult;
}
#RequestMapping(value="/viewallorders", method=RequestMethod.GET)
public String signup(Model model) {
System.out.println("FIRST PART");
WbbOrderStatusForm wbbOrderStatusForm = new WbbOrderStatusForm();
model.addAttribute("wbbOrderStatusForm", wbbOrderStatusForm);
return "viewallorders";
}
}
Mapper class
package com.gm.app.apms.mappers;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.gm.app.apms.model.WbbOrderStatusResult;
public interface WbbCodeMapper
{
#Select("SELECT p1.P3ORDRM0.BUYER_ORDR_NO as distOrderNo, p1.P3ORDRM0.ORDR_YEAR||p1.P3ORDRM0.ORDR_CUST_CD||p1.P3ORDRM0.ORDR_TYPE||p1.P3ORDRM0.ORDR_SEQ as gmdatOrderNo, "
+ "p1.P3ORDRM0.CNFM_DT as cnfmDt, p1.P3ORDRM0.PORT_DEST_CD as packingCode, p1.P9ORDRV1.ORDR_ITEM as orderedItem, "
+ "p1.P9ORDRV1.ORDR_QTY as orderedPcs, Round(p1.P9ORDRV1.ORDR_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as orderedAmt, "
+ "p1.P9ORDRV1.DSTR_ITEM as allocationItem, p1.P9ORDRV1.DSTR_QTY as allocationPcs, Round(p1.P9ORDRV1.DSTR_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as allocationAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.DSTR_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as allocationRate, p1.P9ORDRV1.PICK_ITEM as pickItem, "
+ "p1.P9ORDRV1.PICK_QTY as pickPcs, Round(p1.P9ORDRV1.PICK_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as pickAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.PICK_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as pickRate, p1.P9ORDRV1.PACK_ITEM as packItem, "
+ "p1.P9ORDRV1.PACK_QTY as packPcs, Round(p1.P9ORDRV1.PACK_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as packAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.PICK_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as packRate, p1.P9ORDRV1.CASE_OUT_ITEM as cargoReadyItem, "
+ "p1.P9ORDRV1.CASE_OUT_QTY as cargoReadyPcs, Round(p1.P9ORDRV1.CASE_OUT_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as cargoReadyAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.CASE_OUT_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as cargoReadyRate, p1.P9ORDRV1.SHIP_PEND_ITEM as vanningItem, "
+ "p1.P9ORDRV1.SHIP_PEND_QTY as vanningPcs, Round(p1.P9ORDRV1.SHIP_PEND_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as vanningAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.SHIP_PEND_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as vanningRate, p1.P9ORDRV1.SHIP_ITEM as shippedItem, "
+ "p1.P9ORDRV1.SHIP_QTY as shippedPcs, Round(p1.P9ORDRV1.SHIP_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as shippedAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.SHIP_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as shippedRate, p1.P9ORDRV1.BACK_ORDR_ITEM as balanceItem, "
+ "p1.P9ORDRV1.BACK_ORDR_QTY as balancePcs, Round(p1.P9ORDRV1.BACK_ORDR_AMT*decode(p1.P3ORDRM0.MULTI_EXCH_RATE,1000,1,p1.P3ORDRM0.MULTI_EXCH_RATE),2) as balanceAmt, "
+ "DECODE(p1.P9ORDRV1.ORDR_QTY,0,0,Round((p1.P9ORDRV1.BACK_ORDR_QTY / p1.P9ORDRV1.ORDR_QTY )*100,2)) as balanceRate, decode(p1.P3ORDRM0.CURR,'KRW','USD',p1.P3ORDRM0.CURR) as cur FROM p1.P3ORDRM0, "
+ "p1.P9ORDRV1 WHERE p1.p3ordrm0.ordr_year = p1.P9ORDRV1.ordr_year(+) AND p1.p3ordrm0.ordr_cust_cd = p1.P9ORDRV1.ordr_cust_cd(+) AND p1.p3ordrm0.ordr_type = p1.P9ORDRV1.ordr_type(+) "
+ "AND p1.p3ordrm0.ordr_seq = p1.P9ORDRV1.ordr_seq (+) "
+ "AND p1.P3ORDRM0.CNFM_DT >= #{one} "
+ "AND p1.P3ORDRM0.CNFM_DT <= #{two} "
+ "AND p1.P3ORDRM0.ORDR_TYPE like '%#{three}%' "
+ "AND p1.P3ORDRM0.ORDR_CUST_CD = '#{four}' "
+ "AND p1.P3ORDRM0.ORDRM0_STAT in ('400','500','700') "
+ "AND p1.P3ORDRM0.PORT_DEST_CD LIKE '%#{five}%';")
public List <WbbOrderStatusResult> getResult(String one, String two, String three, String four, String five);
}
Model of form
package com.gm.app.apms.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class WbbOrderStatusForm
{
private String dateFrom;
private String dateTo;
private String orderType;
private String packingCode;
private String distCode;
private String partNo;
private String radioCond;
private String distOrderNo;
private String suppPartNo;
private String suppSrc;
private String caseStatus;
private String caseYear;
private String caseCustCd;
private String caseSm;
private String caseSeq;
private String chk;
private String mod;
private String gmPartNo;
private String suzukiPartNo;
private Collection orderTypeCollection;
private Collection packingCodeCollection;
public WbbOrderStatusForm() {}
public Collection getOrderTypeCollection()
{
ArrayList list = new ArrayList();
//list.add(new LabelValueBean("ALL", ""));
HashMap searchMap = new HashMap();
searchMap.put("cdNo", "E0001");
List result = null;
//List result = (List) WbbCodeService.getInstance().getCodeList(searchMap);
String str = "";
for (int i = 0; i < result.size(); i++)
{
HashMap resultMap = (HashMap) result.get(i);
str = (String) resultMap.get("cdItem");
//list.add(new LabelValueBean(str, (String) resultMap.get("cdValue")));
}
return list;
}
public void setOrderTypeCollection(Collection collection)
{
orderTypeCollection = collection;
}
public Collection getPackingCodeCollection()
{
ArrayList list = new ArrayList();
//list.add(new LabelValueBean("ALL", ""));
HashMap searchMap = new HashMap();
searchMap.put("distCode", distCode);
List result = null;
//List result = (List) WbbCodeService.getInstance().getPackingCodeList(searchMap);
String str = "";
for (int i = 0; i < result.size(); i++)
{
HashMap resultMap = (HashMap) result.get(i);
str = (String) resultMap.get("cdValue");
//list.add(new LabelValueBean(str, (String) resultMap.get("cdValue")));
}
// ������ ���� ��� 1�� ����
if (list.size() == 1)
{
//list.add(new LabelValueBean("1", "1"));
}
return list;
}
public void setPackingCodeCollection(Collection collection)
{
packingCodeCollection = collection;
}
public String getDateFrom()
{
return dateFrom;
}
public void setDateFrom(String dateFrom)
{
this.dateFrom = dateFrom;
}
public String getDateTo()
{
return dateTo;
}
public void setDateTo(String dateTo)
{
this.dateTo = dateTo;
}
public String getOrderType()
{
return orderType;
}
public void setOrderType(String orderType)
{
this.orderType = orderType;
}
public String getPackingCode()
{
return packingCode;
}
public void setPackingCode(String packingCode)
{
this.packingCode = packingCode;
}
public String getDistCode()
{
return distCode;
}
public void setDistCode(String distCode)
{
this.distCode = distCode;
}
public String getPartNo()
{
return partNo;
}
public void setPartNo(String partNo)
{
this.partNo = partNo;
}
public String getRadioCond()
{
return radioCond;
}
public void setRadioCond(String radioCond)
{
this.radioCond = radioCond;
}
public String getDistOrderNo()
{
return distOrderNo;
}
public void setDistOrderNo(String distOrderNo)
{
this.distOrderNo = distOrderNo;
}
public String getSuppPartNo()
{
return suppPartNo;
}
public void setSuppPartNo(String suppPartNo)
{
this.suppPartNo = suppPartNo;
}
public String getSuppSrc()
{
return suppSrc;
}
public void setSuppSrc(String suppSrc)
{
this.suppSrc = suppSrc;
}
public String getCaseStatus()
{
return caseStatus;
}
public void setCaseStatus(String caseStatus)
{
this.caseStatus = caseStatus;
}
public String getCaseYear()
{
return caseYear;
}
public void setCaseYear(String caseYear)
{
this.caseYear = caseYear;
}
public String getCaseCustCd()
{
return caseCustCd;
}
public void setCaseCustCd(String caseCustCd)
{
this.caseCustCd = caseCustCd;
}
public String getCaseSm()
{
return caseSm;
}
public void setCaseSm(String caseSm)
{
this.caseSm = caseSm;
}
public String getCaseSeq()
{
return caseSeq;
}
public void setCaseSeq(String caseSeq)
{
this.caseSeq = caseSeq;
}
public String getChk()
{
return chk;
}
public void setChk(String chk)
{
this.chk = chk;
}
public String getMod()
{
return mod;
}
public void setMod(String mod)
{
this.mod = mod;
}
public String getGmPartNo()
{
return gmPartNo;
}
public void setGmPartNo(String gmPartNo)
{
this.gmPartNo = gmPartNo;
}
public String getSuzukiPartNo()
{
return suzukiPartNo;
}
public void setSuzukiPartNo(String suzukiPartNo)
{
this.suzukiPartNo = suzukiPartNo;
}
}
Model of Result
package com.gm.app.apms.model;
public class WbbOrderStatusResult {
private String distOrderNo;
private String gmdatOrderNo;
private String cnfmDt;
private String packingCode;
private String orderedItem;
private String orderedPcs;
private String orderedAmt;
private String allocationItem;
private String allocationPcs;
private String allocationAmt;
private String allocationRate;
private String pickItem;
private String pickPcs;
private String pickAmt;
private String pickRate;
private String packItem;
private String packPcs;
private String packAmt;
private String packRate;
private String cargoReadyItem;
private String cargoReadyPcs;
private String cargoReadyAmt;
private String cargoReadyRate;
private String vanningItem;
private String vanningPcs;
private String vanningAmt;
private String vanningRate;
private String shippedItem;
private String shippedPcs;
private String shippedAmt;
private String shippedRate;
private String balanceItem;
private String balancePcs;
private String balanceAmt;
private String balanceRate;
private String cur;
public String getDistOrderNo() {
return distOrderNo;
}
public void setDistOrderNo(String distOrderNo) {
this.distOrderNo = distOrderNo;
}
public String getGmdatOrderNo() {
return gmdatOrderNo;
}
public void setGmdatOrderNo(String gmdatOrderNo) {
this.gmdatOrderNo = gmdatOrderNo;
}
public String getCnfmDt() {
return cnfmDt;
}
public void setCnfmDt(String cnfmDt) {
this.cnfmDt = cnfmDt;
}
public String getPackingCode() {
return packingCode;
}
public void setPackingCode(String packingCode) {
this.packingCode = packingCode;
}
public String getOrderedItem() {
return orderedItem;
}
public void setOrderedItem(String orderedItem) {
this.orderedItem = orderedItem;
}
public String getOrderedPcs() {
return orderedPcs;
}
public void setOrderedPcs(String orderedPcs) {
this.orderedPcs = orderedPcs;
}
public String getOrderedAmt() {
return orderedAmt;
}
public void setOrderedAmt(String orderedAmt) {
this.orderedAmt = orderedAmt;
}
public String getAllocationItem() {
return allocationItem;
}
public void setAllocationItem(String allocationItem) {
this.allocationItem = allocationItem;
}
public String getAllocationPcs() {
return allocationPcs;
}
public void setAllocationPcs(String allocationPcs) {
this.allocationPcs = allocationPcs;
}
public String getAllocationAmt() {
return allocationAmt;
}
public void setAllocationAmt(String allocationAmt) {
this.allocationAmt = allocationAmt;
}
public String getAllocationRate() {
return allocationRate;
}
public void setAllocationRate(String allocationRate) {
this.allocationRate = allocationRate;
}
public String getPickItem() {
return pickItem;
}
public void setPickItem(String pickItem) {
this.pickItem = pickItem;
}
public String getPickPcs() {
return pickPcs;
}
public void setPickPcs(String pickPcs) {
this.pickPcs = pickPcs;
}
public String getPickAmt() {
return pickAmt;
}
public void setPickAmt(String pickAmt) {
this.pickAmt = pickAmt;
}
public String getPickRate() {
return pickRate;
}
public void setPickRate(String pickRate) {
this.pickRate = pickRate;
}
public String getPackItem() {
return packItem;
}
public void setPackItem(String packItem) {
this.packItem = packItem;
}
public String getPackPcs() {
return packPcs;
}
public void setPackPcs(String packPcs) {
this.packPcs = packPcs;
}
public String getPackAmt() {
return packAmt;
}
public void setPackAmt(String packAmt) {
this.packAmt = packAmt;
}
public String getPackRate() {
return packRate;
}
public void setPackRate(String packRate) {
this.packRate = packRate;
}
public String getCargoReadyItem() {
return cargoReadyItem;
}
public void setCargoReadyItem(String cargoReadyItem) {
this.cargoReadyItem = cargoReadyItem;
}
public String getCargoReadyPcs() {
return cargoReadyPcs;
}
public void setCargoReadyPcs(String cargoReadyPcs) {
this.cargoReadyPcs = cargoReadyPcs;
}
public String getCargoReadyAmt() {
return cargoReadyAmt;
}
public void setCargoReadyAmt(String cargoReadyAmt) {
this.cargoReadyAmt = cargoReadyAmt;
}
public String getCargoReadyRate() {
return cargoReadyRate;
}
public void setCargoReadyRate(String cargoReadyRate) {
this.cargoReadyRate = cargoReadyRate;
}
public String getVanningItem() {
return vanningItem;
}
public void setVanningItem(String vanningItem) {
this.vanningItem = vanningItem;
}
public String getVanningPcs() {
return vanningPcs;
}
public void setVanningPcs(String vanningPcs) {
this.vanningPcs = vanningPcs;
}
public String getVanningAmt() {
return vanningAmt;
}
public void setVanningAmt(String vanningAmt) {
this.vanningAmt = vanningAmt;
}
public String getVanningRate() {
return vanningRate;
}
public void setVanningRate(String vanningRate) {
this.vanningRate = vanningRate;
}
public String getShippedItem() {
return shippedItem;
}
public void setShippedItem(String shippedItem) {
this.shippedItem = shippedItem;
}
public String getShippedPcs() {
return shippedPcs;
}
public void setShippedPcs(String shippedPcs) {
this.shippedPcs = shippedPcs;
}
public String getShippedAmt() {
return shippedAmt;
}
public void setShippedAmt(String shippedAmt) {
this.shippedAmt = shippedAmt;
}
public String getShippedRate() {
return shippedRate;
}
public void setShippedRate(String shippedRate) {
this.shippedRate = shippedRate;
}
public String getBalanceItem() {
return balanceItem;
}
public void setBalanceItem(String balanceItem) {
this.balanceItem = balanceItem;
}
public String getBalancePcs() {
return balancePcs;
}
public void setBalancePcs(String balancePcs) {
this.balancePcs = balancePcs;
}
public String getBalanceAmt() {
return balanceAmt;
}
public void setBalanceAmt(String balanceAmt) {
this.balanceAmt = balanceAmt;
}
public String getBalanceRate() {
return balanceRate;
}
public void setBalanceRate(String balanceRate) {
this.balanceRate = balanceRate;
}
public String getCur() {
return cur;
}
public void setCur(String cur) {
this.cur = cur;
}
}
Service Interface
package com.gm.app.apms.service;
import java.util.List;
import com.gm.app.apms.model.WbbOrderStatusResult;
public interface IWbbCodeService
{
public List<WbbOrderStatusResult> getTableResult(String one, String two, String three, String four, String five);
}
Service Implementation
package com.gm.app.apms.service;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gm.app.apms.mappers.StudentMapper;
import com.gm.app.apms.mappers.WbbCodeMapper;
import com.gm.app.apms.model.WbbOrderStatusResult;
#Service("IWbbCodeService")
public class WbbCodeService implements IWbbCodeService
{
#Autowired
private WbbCodeMapper wbbCodeMapper;
#Override
public List<WbbOrderStatusResult> getTableResult(String one, String two,
String three, String four, String five) {
return wbbCodeMapper.getResult(one, two, three, four, five);
}
}
Solutions was to use #Param annotation
public List <WbbOrderStatusResult> getResult(#Param("one")String one, #Param("two")String two, #Param("three")String three, #Param("four")String four, #Param("five")String five);
Kothari's own answer would work, but in your xml mapping you could just do
{param1,jdbcType=xxx} #{param2,jdbcType=xxx} etc.....
I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Here you have a tutorial which answers your needs - Android + Gson