I am using JsonArray as input in my REST API. Here I attached my coding part.
After deployment I getting input value as null or internal server error or glass-fish error. Kindly suggest some ideas to resolve this issue.
I tried to change #Consumes(MediaType.APPLICATION_JSON) to #Consumes("application/json") and also command the #XmlRootElement annotation.
This is TransactionData.java class:
#Path("/CreditProcess")
public class TransactionData {
//private Object ipxml;
#POST
#Path("/SOHold")
//#Consumes("application/json")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public TransactionDataResponse Serv(TransactionDataRequest req) throws IOException, JPISException, Exception {
String Status = null, ErrorCode = null;
TransactionDataResponse ObjRes = new TransactionDataResponse();
CommonFunction ObjCF = new CommonFunction();
String SessionId = "";
boolean boolREADINI;
String Webservice = "Hold_Creation";
boolREADINI = ObjCF.ReadINIProperties();
String MISC_ID = "";
String PID = "", SaleOrder = "", Hold_Type = "", Hold_Status = "",
Approved_User = "", Date = "", Remarks = "", Hold_Desc = "", SO_COUNT = "", CH_COUNT = "", flag = "",WorkitemID="";
String Output_data = "", Input_data = "";
DMSXmlResponse Query_Response = null;
SessionId = ObjCF.ConnectCabinet(Webservice);
// PID = req.get();
ObjCF.ReportLog("Input_data request---" + req, Webservice);
JSONArray Data = new JSONArray();
try {
ObjCF.ReportLog("Before Check1---", Webservice);
Data = req.getData();
ObjCF.ReportLog("After Check2---"+Data, Webservice);
int size = Data.size();
for (int row = 0; row < size; row++) {
ObjCF.ReportLog("test1--", Webservice);
JSONObject obj;
HashMap<String, String> passedValues = (HashMap<String, String>) Data.get(row);
ObjCF.ReportLog("test2-- ", Webservice);
// ObjCF.ReportLog("test2--Data.get(i)" + Data.get(i), Webservice);
// obj = (JSONObject) Data.get(i);
for (Entry<String, String> mapTemp : passedValues.entrySet()) {
if (mapTemp.getKey().equalsIgnoreCase("SalesOrder")) {
SaleOrder = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + SaleOrder, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_Type")) {
Hold_Type = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Type" + Hold_Type, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status")) {
Hold_Status = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + Hold_Status, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Approved_User")) {
Approved_User = mapTemp.getValue();
ObjCF.ReportLog("json Approved_User" + Approved_User, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Date_Time")) {
Date = mapTemp.getValue();
ObjCF.ReportLog("json Date" + Date, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Remarks")) {
Remarks = mapTemp.getValue();
ObjCF.ReportLog("json Remarks" + Remarks, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status_Desc")) {
Hold_Desc = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Desc" + Hold_Desc, Webservice);
}
}
}
} catch(Exception e){
}
}
}
This is my TransactionDataRequest.java class:
import com.newgen.Utils.CommonFunction;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONArray;
#XmlRootElement
public class TransactionDataRequest {
private JSONArray Data;
CommonFunction ObjCF = new CommonFunction();
public JSONArray getData() {
ObjCF.ReportLog("Inside getData---", "Hold_Creation");
ObjCF.ReportLog("Inside getData return data---" + Data, "Hold_Creation");
return Data;
}
#XmlElement(name = "Data")
public void setData( JSONArray Data) {
ObjCF.ReportLog("Inside Data:---" + Data, "Hold_Creation");
this.Data = Data;
ObjCF.ReportLog("After this Data:---" + Data, "Hold_Creation");
}
}
Related
I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.
I have 7 protocols, and I want to be shown on the site. But the site shows only 4 protocols, although there are 7 protocols in the JSON file. I decided to check with a debugger, it passes 4 protocols without errors. But starting with the fifth protocol, such an error comes out.
I have error
org.json.JSONException) org.json.JSONException: JSONObject["routes"] not found.
My controller
#Controller
public class LookingGlassController {
private final static String BGP_URL = "http://80.241.0.85/api/protocols/bgp";
private final static String BGP_DETAILS_URL = "http://80.241.0.85/api/protocol/";
private final static String TABLE_URL = "http://80.241.0.85/api/routes/table/";
private final static String ROUT_URL = "http://80.241.0.85/api/route/";
/**
*
* #param lang
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgp")
public ModelAndView bgp(#PathVariable String lang) {
List<BGPData> bgpDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_URL), Charset.forName("UTF-8")));
JSONObject protocols = json.getJSONObject("protocols");
Map<String, Object> prots = protocols.toMap();
for (String prot_name : prots.keySet()) {
JSONObject prot = protocols.getJSONObject(prot_name);
String protocol = prot.getString("protocol");
String neighborAddress = prot.getString("neighbor_address");
String description = prot.getString("description");
Integer asn = prot.getInt("neighbor_as");
String tableName = prot.getString("table");
String status = prot.getString("bgp_state");
Integer routeImport = prot.getJSONObject("routes").getInt("imported");
Integer routeExport = prot.getJSONObject("routes").getInt("exported");
Integer importLimit = prot.getInt("import_limit");
String tableLink = "/" + lang + "/lookingglass/table/" + tableName;
String protocolDetailLink = "/" + lang + "/lookingglass/bgpdetails/" + protocol;
BGPData bgpData = new BGPData();
bgpData.setProtocol(protocol);
bgpData.setProtocolDetailLink(protocolDetailLink);
bgpData.setNaighbord(neighborAddress);
bgpData.setDescription(description);
bgpData.setAsn(asn);
bgpData.setTableName(tableName);
bgpData.setStatus(status);
bgpData.setRouteImport(routeImport);
bgpData.setRouteExport(routeExport);
bgpData.setImportLimit(importLimit);
bgpData.setTableLink(tableLink);
bgpDateList.add(bgpData);
}
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDataList", bgpDateList);
outMap.put("lgSearchData", new LgSearchData());
return new ModelAndView("/site/lookingglass/bgp", outMap);
}
/**
*
* #param lang
* #param protocol
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgpdetails/{protocol}")
public ModelAndView bgp_details(#PathVariable String lang, #PathVariable String protocol) {
BGPDetailData bgpDetalisData = new BGPDetailData();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_DETAILS_URL + protocol), Charset.forName("UTF-8")));
JSONObject protocolJs = json.getJSONObject("protocol");
String bird_protocol = protocolJs.getString("bird_protocol");
String state = protocolJs.getString("state");
String state_changed = protocolJs.getString("state_changed");
String connection = protocolJs.getString("connection");
String description = protocolJs.getString("description");
Integer preference = protocolJs.getInt("preference");
String input_filter = protocolJs.getString("input_filter");
String output_filter = protocolJs.getString("output_filter");
Integer import_limit = protocolJs.getInt("import_limit");
String limit_action = protocolJs.getString("limit_action");
Integer routes_imported = protocolJs.getJSONObject("routes").getInt("imported");
Integer routes_exported = protocolJs.getJSONObject("routes").getInt("exported");
Integer routes_preferred = protocolJs.getJSONObject("routes").getInt("preferred");
JSONObject jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_updates");
String route_change_import_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_withdraws");
String route_change_import_withdraws = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_updates");
String route_change_export_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_withdraws");
String route_change_export_withdraws = getRouteChange(jsO);
String bgp_state = protocolJs.getString("bgp_state");
String neighbor_address = protocolJs.getString("neighbor_address");
Integer neighbor_as = protocolJs.getInt("neighbor_as");
String neighbor_id = "";
try {
neighbor_id = protocolJs.getString("neighbor_id");
} catch (JSONException ex) {
}
String neighbor_capabilities = "";
try {
JSONArray ar = protocolJs.getJSONArray("neighbor_capabilities");
for (Object aspo : ar) {
neighbor_capabilities += (String) aspo + " ";
}
} catch (JSONException ex) {
neighbor_capabilities = "n/a";
}
String session = "";
try {
JSONArray ar = protocolJs.getJSONArray("bgp_session");
for (Object aspo : ar) {
session += (String) aspo + " ";
}
} catch (JSONException ex) {
session = "n/a";
}
String source_address = "";
try {
source_address = protocolJs.getString("source_address");
} catch (JSONException ex) {
session = "n/a";
}
Integer hold_timer = null;
try {
hold_timer = protocolJs.getInt("hold_timer");
} catch (JSONException ex) {
session = "n/a";
}
Integer route_limit_at = null;
try {
route_limit_at = protocolJs.getInt("route_limit_at");
} catch (JSONException ex) {
session = "n/a";
}
Integer keepalive = null;
try {
keepalive = protocolJs.getInt("keepalive");
} catch (JSONException ex) {
session = "n/a";
}
bgpDetalisData.setProtocol(protocol);
bgpDetalisData.setBird_protocol(bird_protocol);
bgpDetalisData.setState(state);
bgpDetalisData.setState_changed(state_changed);
bgpDetalisData.setConnection(connection);
bgpDetalisData.setDescription(description);
bgpDetalisData.setPreference(preference);
bgpDetalisData.setInput_filter(input_filter);
bgpDetalisData.setOutput_filter(output_filter);
bgpDetalisData.setImport_limit(import_limit);
bgpDetalisData.setLimit_action(limit_action);
bgpDetalisData.setRoutes_imported(routes_imported);
bgpDetalisData.setRoutes_exported(routes_exported);
bgpDetalisData.setRoutes_preferred(routes_preferred);
bgpDetalisData.setRoute_change_import_updates(route_change_import_updates);
bgpDetalisData.setRoute_change_import_withdraws(route_change_import_withdraws);
bgpDetalisData.setRoute_change_export_updates(route_change_export_updates);
bgpDetalisData.setRoute_change_export_withdraws(route_change_export_withdraws);
bgpDetalisData.setBgp_state(bgp_state);
bgpDetalisData.setNeighbor_address(neighbor_address);
bgpDetalisData.setNeighbor_as(neighbor_as);
bgpDetalisData.setNeighbor_id(neighbor_id);
bgpDetalisData.setNeighbor_capabilities(neighbor_capabilities);
bgpDetalisData.setBgp_session(session);
bgpDetalisData.setSource_address(source_address);
bgpDetalisData.setHold_timer(hold_timer);
bgpDetalisData.setRoute_limit_at(route_limit_at);
bgpDetalisData.setKeepalive(keepalive);
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDetails", bgpDetalisData);
return new ModelAndView("/site/lookingglass/bgp_details", outMap);
}
/**
*
* #param jsO
* #return
*/
private String getRouteChange(JSONObject jsO) {
String out = "";
try {
Integer received = jsO.getInt("received");
out += "recived: " + received + ", ";
} catch (JSONException ex) {
}
try {
Integer rejected = jsO.getInt("rejected");
out += "rejected: " + rejected + ", ";
} catch (JSONException ex) {
}
try {
Integer filtered = jsO.getInt("filtered");
out += "filtered: " + filtered + ", ";
} catch (JSONException ex) {
}
try {
Integer ignored = jsO.getInt("ignored");
out += "ignored: " + ignored + ", ";
} catch (JSONException ex) {
}
try {
Integer accepted = jsO.getInt("accepted");
out += "accepted: " + accepted + ", ";
} catch (JSONException ex) {
}
return out.substring(0, out.length() - 2);
}
/**
*
* #param lang
* #param name
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/table/{name}")
public ModelAndView table(#PathVariable String lang, #PathVariable String name) {
List<TableData> tableDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(TABLE_URL + name), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
Integer communities = 0;
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
try {
JSONArray ar1 = rout.getJSONObject("bgp").getJSONArray("communities");
communities = ar1.length();
} catch (JSONException ex) {
}
String networkLink = "/" + lang + "/lookingglass/route/" + network;
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setNetworkLink(networkLink);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setCommunities(communities);
tableData.setAspath(aspath);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException ex) {
name = "UNKNOWN";
} catch (JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("tableName", name);
return new ModelAndView("/site/lookingglass/table", outMap);
}
/**
*
* #param lang
* #param ip
* #param mask
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/route/{ip}/{mask}")
public ModelAndView rout(#PathVariable String lang, #PathVariable String ip, #PathVariable String mask) {
String net;
List<TableData> tableDateList = new ArrayList<>();
try {
net = ip + "/" + mask;
String url = ROUT_URL + URLEncoder.encode(net, "UTF-8");
JSONObject json = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
String inter_face = rout.getString("interface");
String age = rout.getString("age");
String from_protocol = rout.getString("from_protocol");
String origin = rout.getJSONObject("bgp").getString("origin");
Integer med = null;
try {
med = rout.getJSONObject("bgp").getInt("med");
} catch (JSONException ex) {
}
String localPref = rout.getJSONObject("bgp").getString("local_pref");
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
String type = "";
JSONArray ar1 = rout.getJSONArray("type");
for (Object t : ar1) {
type += (String) t + " ";
}
String communitiesList = "";
try {
JSONArray ar2 = rout.getJSONObject("bgp").getJSONArray("communities");
for (Object o : ar2) {
JSONArray ar3 = (JSONArray) o;
communitiesList += "(";
int index = 0;
for (Object o1 : ar3) {
if (index > 0) {
communitiesList += ", ";
}
communitiesList += (Integer) o1;
index++;
}
communitiesList += ") ";
}
} catch (JSONException ex) {
}
if (communitiesList.isEmpty()) {
communitiesList = null;
}
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setAspath(aspath);
tableData.setInter_face(inter_face);
tableData.setAge(age);
tableData.setFromProtocol(from_protocol);
tableData.setType(type);
tableData.setOrigin(origin);
tableData.setLocalPref(localPref);
tableData.setCommunitiesList(communitiesList);
tableData.setMed(med);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException | JSONException ex) {
net = "UNKNOWN";
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("net", net);
return new ModelAndView("/site/lookingglass/route", outMap);
}
/**
*
* #param lang
* #param lgSearchData
* #param result
* #param model
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/search")
public ModelAndView search(#PathVariable String lang,
#Valid #ModelAttribute("lgSearchData") LgSearchData lgSearchData,
BindingResult result,
ModelMap model) {
String ip = lgSearchData.getIp();
if (ip == null || ip.isEmpty()) {
return new ModelAndView("redirect:/" + lang + "/lookingglass/bgp");
}
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(ROUT_URL + URLEncoder.encode(ip, "UTF-8")), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
JSONObject rout = routes.getJSONObject(0);
if (rout != null) {
String network = rout.getString("network");
return new ModelAndView("redirect:/" + lang + "/lookingglass/route/" + network);
}
} catch (IOException | JSONException ex) {
}
return new ModelAndView("/site/lookingglass/bgp");
}
}
I have 7 protocols
enter image description here
On site show only 4 protocols(((
enter image description here
Information about protocol
enter image description here
Ok, this issue is because it is not found routes field in JSON object then you need to check if the JSON object has this field, I created a method called getRoutesAsJSONObject(JSONObject jsonObject) this method check if a JSON object has routes then return the routes as JSON object else creates a JSON Object and adds routes as JSONObject with imported, exported and preferred values to 0.
#Controller
public class LookingGlassController {
private final static String BGP_URL = "http://80.241.0.85/api/protocols/bgp";
private final static String BGP_DETAILS_URL = "http://80.241.0.85/api/protocol/";
private final static String TABLE_URL = "http://80.241.0.85/api/routes/table/";
private final static String ROUT_URL = "http://80.241.0.85/api/route/";
/**
*
* #param lang
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgp")
public ModelAndView bgp(#PathVariable String lang) {
List<BGPData> bgpDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_URL), Charset.forName("UTF-8")));
JSONObject protocols = json.getJSONObject("protocols");
Map<String, Object> prots = protocols.toMap();
for (String prot_name : prots.keySet()) {
JSONObject prot = protocols.getJSONObject(prot_name);
String protocol = prot.getString("protocol");
String neighborAddress = prot.getString("neighbor_address");
String description = prot.getString("description");
Integer asn = prot.getInt("neighbor_as");
String tableName = prot.getString("table");
String status = prot.getString("bgp_state");
JSONObject routesAsJSONObject = getRoutesAsJSONObject(prot);
Integer routeImport = routesAsJSONObject.getInt("imported");
Integer routeExport = routesAsJSONObject.getInt("exported");
Integer importLimit = prot.getInt("import_limit");
String tableLink = "/" + lang + "/lookingglass/table/" + tableName;
String protocolDetailLink = "/" + lang + "/lookingglass/bgpdetails/" + protocol;
BGPData bgpData = new BGPData();
bgpData.setProtocol(protocol);
bgpData.setProtocolDetailLink(protocolDetailLink);
bgpData.setNaighbord(neighborAddress);
bgpData.setDescription(description);
bgpData.setAsn(asn);
bgpData.setTableName(tableName);
bgpData.setStatus(status);
bgpData.setRouteImport(routeImport);
bgpData.setRouteExport(routeExport);
bgpData.setImportLimit(importLimit);
bgpData.setTableLink(tableLink);
bgpDateList.add(bgpData);
}
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDataList", bgpDateList);
outMap.put("lgSearchData", new LgSearchData());
return new ModelAndView("/site/lookingglass/bgp", outMap);
}
/**
*
* #param lang
* #param protocol
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgpdetails/{protocol}")
public ModelAndView bgp_details(#PathVariable String lang, #PathVariable String protocol) {
BGPDetailData bgpDetalisData = new BGPDetailData();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_DETAILS_URL + protocol), Charset.forName("UTF-8")));
JSONObject protocolJs = json.getJSONObject("protocol");
String bird_protocol = protocolJs.getString("bird_protocol");
String state = protocolJs.getString("state");
String state_changed = protocolJs.getString("state_changed");
String connection = protocolJs.getString("connection");
String description = protocolJs.getString("description");
Integer preference = protocolJs.getInt("preference");
String input_filter = protocolJs.getString("input_filter");
String output_filter = protocolJs.getString("output_filter");
Integer import_limit = protocolJs.getInt("import_limit");
String limit_action = protocolJs.getString("limit_action");
JSONObject routesAsJSONObject = getRoutesAsJSONObject(protocolJs);
Integer routes_imported = routesAsJSONObject.getInt("imported");
Integer routes_exported = routesAsJSONObject.getInt("exported");
Integer routes_preferred = routesAsJSONObject.getInt("preferred");
JSONObject jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_updates");
String route_change_import_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_withdraws");
String route_change_import_withdraws = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_updates");
String route_change_export_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_withdraws");
String route_change_export_withdraws = getRouteChange(jsO);
String bgp_state = protocolJs.getString("bgp_state");
String neighbor_address = protocolJs.getString("neighbor_address");
Integer neighbor_as = protocolJs.getInt("neighbor_as");
String neighbor_id = "";
try {
neighbor_id = protocolJs.getString("neighbor_id");
} catch (JSONException ex) {
}
String neighbor_capabilities = "";
try {
JSONArray ar = protocolJs.getJSONArray("neighbor_capabilities");
for (Object aspo : ar) {
neighbor_capabilities += (String) aspo + " ";
}
} catch (JSONException ex) {
neighbor_capabilities = "n/a";
}
String session = "";
try {
JSONArray ar = protocolJs.getJSONArray("bgp_session");
for (Object aspo : ar) {
session += (String) aspo + " ";
}
} catch (JSONException ex) {
session = "n/a";
}
String source_address = "";
try {
source_address = protocolJs.getString("source_address");
} catch (JSONException ex) {
session = "n/a";
}
Integer hold_timer = null;
try {
hold_timer = protocolJs.getInt("hold_timer");
} catch (JSONException ex) {
session = "n/a";
}
Integer route_limit_at = null;
try {
route_limit_at = protocolJs.getInt("route_limit_at");
} catch (JSONException ex) {
session = "n/a";
}
Integer keepalive = null;
try {
keepalive = protocolJs.getInt("keepalive");
} catch (JSONException ex) {
session = "n/a";
}
bgpDetalisData.setProtocol(protocol);
bgpDetalisData.setBird_protocol(bird_protocol);
bgpDetalisData.setState(state);
bgpDetalisData.setState_changed(state_changed);
bgpDetalisData.setConnection(connection);
bgpDetalisData.setDescription(description);
bgpDetalisData.setPreference(preference);
bgpDetalisData.setInput_filter(input_filter);
bgpDetalisData.setOutput_filter(output_filter);
bgpDetalisData.setImport_limit(import_limit);
bgpDetalisData.setLimit_action(limit_action);
bgpDetalisData.setRoutes_imported(routes_imported);
bgpDetalisData.setRoutes_exported(routes_exported);
bgpDetalisData.setRoutes_preferred(routes_preferred);
bgpDetalisData.setRoute_change_import_updates(route_change_import_updates);
bgpDetalisData.setRoute_change_import_withdraws(route_change_import_withdraws);
bgpDetalisData.setRoute_change_export_updates(route_change_export_updates);
bgpDetalisData.setRoute_change_export_withdraws(route_change_export_withdraws);
bgpDetalisData.setBgp_state(bgp_state);
bgpDetalisData.setNeighbor_address(neighbor_address);
bgpDetalisData.setNeighbor_as(neighbor_as);
bgpDetalisData.setNeighbor_id(neighbor_id);
bgpDetalisData.setNeighbor_capabilities(neighbor_capabilities);
bgpDetalisData.setBgp_session(session);
bgpDetalisData.setSource_address(source_address);
bgpDetalisData.setHold_timer(hold_timer);
bgpDetalisData.setRoute_limit_at(route_limit_at);
bgpDetalisData.setKeepalive(keepalive);
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDetails", bgpDetalisData);
return new ModelAndView("/site/lookingglass/bgp_details", outMap);
}
/**
*
* #param jsO
* #return
*/
private String getRouteChange(JSONObject jsO) {
String out = "";
try {
Integer received = jsO.getInt("received");
out += "recived: " + received + ", ";
} catch (JSONException ex) {
}
try {
Integer rejected = jsO.getInt("rejected");
out += "rejected: " + rejected + ", ";
} catch (JSONException ex) {
}
try {
Integer filtered = jsO.getInt("filtered");
out += "filtered: " + filtered + ", ";
} catch (JSONException ex) {
}
try {
Integer ignored = jsO.getInt("ignored");
out += "ignored: " + ignored + ", ";
} catch (JSONException ex) {
}
try {
Integer accepted = jsO.getInt("accepted");
out += "accepted: " + accepted + ", ";
} catch (JSONException ex) {
}
return out.substring(0, out.length() - 2);
}
/**
*
* #param lang
* #param name
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/table/{name}")
public ModelAndView table(#PathVariable String lang, #PathVariable String name) {
List<TableData> tableDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(TABLE_URL + name), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
Integer communities = 0;
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
try {
JSONArray ar1 = rout.getJSONObject("bgp").getJSONArray("communities");
communities = ar1.length();
} catch (JSONException ex) {
}
String networkLink = "/" + lang + "/lookingglass/route/" + network;
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setNetworkLink(networkLink);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setCommunities(communities);
tableData.setAspath(aspath);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException ex) {
name = "UNKNOWN";
} catch (JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("tableName", name);
return new ModelAndView("/site/lookingglass/table", outMap);
}
/**
*
* #param lang
* #param ip
* #param mask
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/route/{ip}/{mask}")
public ModelAndView rout(#PathVariable String lang, #PathVariable String ip, #PathVariable String mask) {
String net;
List<TableData> tableDateList = new ArrayList<>();
try {
net = ip + "/" + mask;
String url = ROUT_URL + URLEncoder.encode(net, "UTF-8");
JSONObject json = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
String inter_face = rout.getString("interface");
String age = rout.getString("age");
String from_protocol = rout.getString("from_protocol");
String origin = rout.getJSONObject("bgp").getString("origin");
Integer med = null;
try {
med = rout.getJSONObject("bgp").getInt("med");
} catch (JSONException ex) {
}
String localPref = rout.getJSONObject("bgp").getString("local_pref");
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
String type = "";
JSONArray ar1 = rout.getJSONArray("type");
for (Object t : ar1) {
type += (String) t + " ";
}
String communitiesList = "";
try {
JSONArray ar2 = rout.getJSONObject("bgp").getJSONArray("communities");
for (Object o : ar2) {
JSONArray ar3 = (JSONArray) o;
communitiesList += "(";
int index = 0;
for (Object o1 : ar3) {
if (index > 0) {
communitiesList += ", ";
}
communitiesList += (Integer) o1;
index++;
}
communitiesList += ") ";
}
} catch (JSONException ex) {
}
if (communitiesList.isEmpty()) {
communitiesList = null;
}
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setAspath(aspath);
tableData.setInter_face(inter_face);
tableData.setAge(age);
tableData.setFromProtocol(from_protocol);
tableData.setType(type);
tableData.setOrigin(origin);
tableData.setLocalPref(localPref);
tableData.setCommunitiesList(communitiesList);
tableData.setMed(med);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException | JSONException ex) {
net = "UNKNOWN";
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("net", net);
return new ModelAndView("/site/lookingglass/route", outMap);
}
/**
*
* #param lang
* #param lgSearchData
* #param result
* #param model
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/search")
public ModelAndView search(#PathVariable String lang,
#Valid #ModelAttribute("lgSearchData") LgSearchData lgSearchData,
BindingResult result,
ModelMap model) {
String ip = lgSearchData.getIp();
if (ip == null || ip.isEmpty()) {
return new ModelAndView("redirect:/" + lang + "/lookingglass/bgp");
}
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(ROUT_URL + URLEncoder.encode(ip, "UTF-8")), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
JSONObject rout = routes.getJSONObject(0);
if (rout != null) {
String network = rout.getString("network");
return new ModelAndView("redirect:/" + lang + "/lookingglass/route/" + network);
}
} catch (IOException | JSONException ex) {
}
return new ModelAndView("/site/lookingglass/bgp");
}
private JSONObject getRoutesAsJSONObject(JSONObject jsonObject) {
if (jsonObject.has("routes")) {
try {
return jsonObject.getJSONObject("routes");
} catch (JSONException exception) {
exception.printStackTrace();
}
}
JSONObject routesJSON = new JSONObject();
try {
routesJSON.put("imported", 0);
routesJSON.put("exported", 0);
routesJSON.put("preferred", 0);
} catch (JSONException e) {
e.printStackTrace();
}
return routesJSON;
}
}
I'm working in a project where after retrieving JSON from a URL, I need to manipulate the JSON file. I retrieved my JSON file from the following link:
http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313
That JSON file contains information on a specific Service Station in France such as:
The Station Service details (steet,name,mark ...)
The Services (Washing,WC ....)
And the most importantly! The recent price of fuels
For that, I've tried to follow a solution given here at stackoverflow, by other user, to a similar problem. You can see:
Android JSON parsing of multiple JSONObjects inside JSONObject
Here is my code (full method):
#GET
#Path("/DecouvrirJSONInfo/{stationServiceInfo}")
public StationService DecouvrirJSON(#PathParam ("stationServiceInfo") String jsonString) throws JSONException
{
JSONObject myResponse = new JSONObject(jsonString);
String nom;
String carburantGazole, carburantSP95, carburantSP98, carburantGPL;
float prixCarburantGazole, prixCarburantSP95, prixSP98, prixGPL;
Date dtActGazole, dtActSP98, dtActSP95,dtActGPL;
StationService actuelStationService = new StationService();
Carburant carburant = new Carburant();
List<Carburant> carburants = new ArrayList<Carburant>();
try
{
//nom = myResponse.getString("nom");
Iterator<String> keysRoot = myResponse.keys();
while (keysRoot.hasNext())
{
String rootKey = keysRoot.next();
if(rootKey == "properties")
{
JSONObject innerZeroJObject = myResponse.getJSONObject(rootKey);
Iterator<String> keys = innerZeroJObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
//Log.v("**********", "**********");
//Log.v("category key", key);
if(key=="carburant")
{
JSONObject innerJObject = myResponse.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
if(innerKkey == "1") // gazole
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantGazole = innerIIJObject.getString("carburant");
dtActGazole = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixCarburantGazole = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantGazole);
carburant.DefinirPrixCarburant(prixCarburantGazole);
carburants.add(carburant);
carburant = new Carburant();
}
}
else if(innerKkey == "2") // Sp95
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantSP95 = innerIIJObject.getString("carburant");
dtActSP95 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixCarburantSP95 = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantSP95);
carburant.DefinirPrixCarburant(prixCarburantSP95);
carburants.add(carburant);
carburant = new Carburant();
}
}
else if(innerKkey == "3") // SP98
{
JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
Iterator<String> innerIKeys = innerIIJObject.keys();
while( innerIKeys.hasNext() )
{
carburantSP98 = innerIIJObject.getString("carburant");
dtActSP98 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse(innerIIJObject.getString("maj"));
prixSP98 = Float.parseFloat( innerIIJObject.getString("prix"));
carburant.DefinirNomCarburant(carburantSP98);
carburant.DefinirPrixCarburant(prixSP98);
carburants.add(carburant);
carburant = new Carburant();
}
}
//String value = innerJObject.getString(innerKkey);
//Log.v("key = "+key, "value = "+value);
}
}
}
}
}
//actuelStationService.DefinirNomStationService(nom);
actuelStationService.DefinirCarburants(carburants);
}
catch(Exception ex)
{
}
return actuelStationService;
}
Can you help me and find the error(s). Please see the first link, which contains the JSON response.
I would recommend using library like JsonPath to search through the json instead of iterating manually. If you can use JsonPath in your project, here is a way to do this:
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
public class SearchJson {
public static void main(String[] args) throws Exception {
URL url = new URL("http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313");
URLConnection connection = url.openConnection();
String jsonString = toString(new InputStreamReader(connection.getInputStream()));
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString);
Integer nbDesCarburants = (Integer) JsonPath.read(document, "$.properties.carburants.length()");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Carburant> carburants = new ArrayList<>();
for (int i = 0; i < nbDesCarburants; i++) {
Map<String, Object> carburantMap = (Map<String, Object>) JsonPath.read(document,
"$.properties.carburants[" + i + "]");
String nom = (String) carburantMap.get("carburant");
Date maj = simpleDateFormat.parse(carburantMap.get("maj").toString());
float prix = Float.parseFloat(carburantMap.get("prix").toString());
Carburant carburant = new Carburant(nom, maj, prix);
carburants.add(carburant);
}
for (Carburant carburant : carburants) {
System.out.println(carburant);
}
}
static class Carburant {
private final String nom;
private final Date date;
private final float prix;
public Carburant(String nom, Date date, float prix) {
super();
this.nom = nom;
this.date = date;
this.prix = prix;
}
#Override
public String toString() {
return "Carburant [nom=" + nom + ", date=" + date + ", prix=" + prix + "]";
}
}
public static String toString(InputStreamReader reader) throws IOException {
char[] charBuf = new char[1024];
int read = reader.read(charBuf, 0, 1024);
StringBuilder sb = new StringBuilder();
while (read != -1) {
sb.append(new String(charBuf));
charBuf = new char[1024];
read = reader.read(charBuf, 0, 1024);
}
sb.append(new String(charBuf));
return sb.toString();
}
}
To run the example, make sure you have JsonPath jar in your classpath or if you are using maven to build your project, add json-path in your dependencies.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.3.0</version>
</dependency>
I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject
my json string is
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
First of all, you need to create the class that you are going to map JSON inside.
Fortunately, there is a website that can do it for you here
secondly, you can use google Gson library for easy mapping
1. add the dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. from your object to JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
3. from JSON to object .
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
for more information about gson see this tutorial.
If you use JsonObject, you can define your entity class as this:
public class Entity {
String type;
List<Crops> crops;
}
public class Crops {
long crop_id;
String crop_name;
List<CropDetail> crop_details;
}
public class CropDetail {
String created_id;
List<Question> questions;
}
public class Question {
int plants;
String planted_by;
}
public void convert(String json){
JsonObject jsonObject = new JsonObject(jsonstring);
Entity entity = new Entity();
entity.type = jsonObject.optString("type");
entity.crops = new ArrayList<>();
JsonArray arr = jsonObject.optJSONArray("crops");
for (int i = 0; i < arr.length(); i++) {
JSONObject crops = arr.optJSONObject(i);
Crops cps = new Crops();
cps.crop_id = crops.optLong("crop_id");
cps.crop_name = crops.optString("crop_name");
cps.crop_details = new ArrayList<>();
JsonArray details = crops.optJsonArray("crop_details");
// some other serialize codes
..........
}
}
So you can nested to convert your json string to an entity class.
Here is how I do it without any packages, this do the work for me for small use cases:
My modal class:
package prog.com.quizapp.models;
import org.json.JSONException;
import org.json.JSONObject;
public class Question {
private String question;
private String correct_answer;
private String answer_a;
private String answer_b;
private String answer_c;
private String answer_d;
public Question() {
}
public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
this.question = question;
this.answer_a = answer_a;
this.answer_b = answer_b;
this.answer_c = answer_c;
this.answer_d = answer_d;
this.correct_answer = correct_answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCorrect_answer() {
return correct_answer;
}
public void setCorrect_answer(String correct_answer) {
this.correct_answer = correct_answer;
}
public String getAnswer_a() {
return answer_a;
}
public void setAnswer_a(String answer_a) {
this.answer_a = answer_a;
}
public String getAnswer_b() {
return answer_b;
}
public void setAnswer_b(String answer_b) {
this.answer_b = answer_b;
}
public String getAnswer_c() {
return answer_c;
}
public void setAnswer_c(String answer_c) {
this.answer_c = answer_c;
}
public String getAnswer_d() {
return answer_d;
}
public void setAnswer_d(String answer_d) {
this.answer_d = answer_d;
}
#Override
public String toString() {
return "Question{" +
"question='" + question + '\'' +
", correct_answer='" + correct_answer + '\'' +
", answer_a='" + answer_a + '\'' +
", answer_b='" + answer_b + '\'' +
", answer_c='" + answer_c + '\'' +
", answer_d='" + answer_d + '\'' +
'}';
}
public static Question fromJson(JSONObject obj) throws JSONException {
return new Question(
obj.getString("question"),
obj.getString("answer_a"),
obj.getString("answer_b"),
obj.getString("answer_c"),
obj.getString("answer_d"),
obj.getString("correct_answer"));
}
}
And I have another class to get the json file from assets directory and mapped JsonObject to my model class Question:
package prog.com.quizapp.utils;
import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import prog.com.quizapp.models.Question;
public class JsonSqlQueryMapper {
private Context mContext;
public JsonSqlQueryMapper(Context context) {
this.mContext = context;
}
private static final String TAG = "JsonSqlQueryMapper";
public JSONObject loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("quiz_app.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
return quizObject;
} catch (Exception e) {
Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
return null;
}
}
public ArrayList<Question> generateInsertQueryForJsonObjects() {
ArrayList<Question> questions = new ArrayList<>();
JSONObject jsonObject = loadJSONFromAsset();
try {
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject value = jsonObject.getJSONObject(key);
Question question = Question.fromJson(value.getJSONObject("question_two"));
questions.add(question);
Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
}
} catch (Exception e) {
e.printStackTrace();
}
return questions;
}
}
And in my MainActivity -> onCreate:
JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
mapper.generateInsertQueryForJsonObjects();
To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json
Regards!
I am trying the read the request attributes and change them using Filter, so that in Controller I would receive changed values as per my need. but the changes I did in Filter is not reflected in #RequestParam.
My controller:
public Response getDetails(HttpServletRequest req, #RequestParam(required = false) String userId) {
System.out.println("attrib in request:"+req.getParameter("userId"));
System.out.println("attrib in RequestParam:"+userId);
}
My Filter:
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
System.out.println("inside filter---------------------------");
HtmlRequestWrapper req = new HtmlRequestWrapper(request);
chain.doFilter(req, response);
} catch (Exception ex) {
request.setAttribute("errorMessage", ex);
// request.getRequestDispatcher("/WEB-INF/views/jsp/error.jsp").forward(request,
// response);
}
}
My HttpServletRequestWrapper(HtmlRequestWrapper):
public class HtmlRequestWrapper extends HttpServletRequestWrapper {
public HtmlRequestWrapper(ServletRequest request) {
super((HttpServletRequest) request);
}
public String sanitize(String input) {
String result = "";
result = input + "bla bla";
return result;
}
public String getParameter(String paramName) {
String value = super.getParameter(paramName);
value = sanitize(value);
return value;
}
public String[] getParameterValues() {
String values[] = null;
// String values[] = request.getParameterValues(paramName);
for (Enumeration<String> en = super.getParameterNames(); en.hasMoreElements();) {
String paramName = (String) en.nextElement();
values = super.getParameterValues(paramName);
int n = values.length;
for (int i = 0; i < n; i++) {
System.out.println("param val before: " + values[i]);
values[i] = sanitize(values[i]);
System.out.println("param val after: " + values[i]);
}
}
return values;
}
public Map<String, String[]> getParameterMap() {
Map<String, String[]> paramMap = new HashMap<>();
String values[] = null;
for (Enumeration<String> en = super.getParameterNames(); en.hasMoreElements();) {
String paramName = (String) en.nextElement();
values = super.getParameterValues(paramName);
int n = values.length;
for (int i = 0; i < n; i++) {
System.out.println("param val before in map: " + values[i]);
values[i] = sanitize(values[i]);
System.out.println("param val after in map: " + values[i]);
}
paramMap.put(paramName, values);
this.getRequest().setAttribute(paramName, values);
}
return Collections.unmodifiableMap(paramMap);
}
}
as you can see i am just trying to append some text to the attribute values.In real scenario would be cleaning and appending with some logic.
Note: In my controller I get the changed value in req.getParameter("userId") but #RequestParam(required = false) String userId contains the same old values passed down from the actual request.
I want #RequestParam(required = false) String userId to reflect the changes in req.getParameter("userId").
updating(Adding WebConfig class):
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ServiceInterceptor());
}
#Bean
public Filter htmlFilter() {
return new HtmlFilter();
}