org.json.JSONException: Missing value at character 2 - java
I am trying to parse the below json response using following code but the code is working fine on normal eclipse program but failing on tomcat (java 1.8)
2016-12-20 00:18:17,146 DEBUG c.a.f.u.s.UpdateFileUploadData [Thread-35]
sTempOutput::"[{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
000913\"},{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
001473\"},{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
001474\"}]"
2016-12-20 00:18:17,146 DEBUG c.a.f.u.s.UpdateFileUploadData [Thread-35]
transformed:[{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
000913\"},{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
001473\"},{\"Status\":\"Success\",\"MonthlyReportId\":\"R/I -
001474\"}]
jsonObject = jsonObject.replaceAll("\\\"", "\"");
if(jsonObject.startsWith("\"")){
jsonObject = jsonObject.substring(1, jsonObject.length()-1);
} // replacing the " from start and end.
if (logger.isDebugEnabled()) {
logger.debug("transformed:{}", jsonObject);
}
org.json.JSONArray array = new org.json.JSONArray(jsonObject);
if (logger.isDebugEnabled()) {
logger.debug("array:::{}", array);
}
DBAdapter dbAdapter = new DBAdapter();
for (int start = 0 ;start<array.length(); start++){
JSONObject object = array.getJSONObject(start);
String status = (String)object.get("Status");
String monthlyReportId = (String)object.get("MonthlyReportId");
if (logger.isDebugEnabled()) {
logger.debug("status:::{}", status);
logger.debug("monthlyReportId:::{}", monthlyReportId);
}
}
This is killing me. I have also tried it -
jsonObject = jsonObject.replaceAll("(\\r|\\n|\\r\\n)+", "");
jsonObject = jsonObject.replaceAll("\\\"", "\"");
rest remains the same.
Related
Rally Java: Duplicate test case getting created
I have built a Rally dependency, which auto creates test case, folder in Test Plan. While creating test case it checks first if there any any existing test case with same name, else it creates new test case. This was working while total test case size was small, while the test case size increased, i am seeing duplicate test cases are created. So I made thread to wait for few seconds (Thread.sleep(8000)) after checking existing scenarios and then creating new scenario. It works by this way. Is there better way to handle & implement this to handle any size of test case. Please advice. String tcName = rallyMethods.getTestScenarios(parentFolder, scenarioName); Thread.sleep(8000); if (tcName == null) { rallyMethods.createTestCase(parentFolder, scenarioName); Thread.sleep(8000); } else { rallyMethods.updateTestCase(parentFolder, scenarioName); Thread.sleep(8000); } public String getTestScenarios(String parentFolderName, String ScenarioName) throws Throwable { String sName = null; String pFolder; QueryRequest testCaseRequest = new QueryRequest("TestCase"); testCaseRequest.setLimit(Integer.MAX_VALUE); testCaseRequest.setPageSize(Integer.MAX_VALUE); testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "Workspace", "Project", "TestFolder")); testCaseRequest.setQueryFilter(new QueryFilter("Name", "=", ScenarioName)); testCaseRequest.setWorkspace(WORKSPACE_ID); testCaseRequest.setProject(PROJECT_ID); QueryResponse testCaseQueryResponse = query(testCaseRequest); int testCaseCount = testCaseQueryResponse.getTotalResultCount(); // System.out.println("TestCaseCount:" + testCaseCount); for (int i = 0; i < testCaseCount; i++) { JsonObject scenarioObj = testCaseQueryResponse.getResults().get(i).getAsJsonObject(); String scenarioName = String.valueOf(scenarioObj.get("Name").getAsString()); JsonElement pFolderObj = scenarioObj.get("TestFolder"); if (!(pFolderObj.isJsonNull())) { JsonObject tFolderObj = scenarioObj.get("TestFolder").getAsJsonObject(); pFolder = String.valueOf(tFolderObj.get("Name").getAsString()); if (parentFolderName.equalsIgnoreCase(pFolder)) { sName = scenarioName; logger.info("Test Scenarios identified in Rally: " + sName); } else { logger.info("Scenario, " + ScenarioName + " not found, New Scenario will be created in Rally"); } } } return sName; } public void createTestCase(String parentFolderName, String testCaseName) throws Throwable { String tcName = null; String userID = readUser(); // Query Child Folders: QueryRequest testFolderRequest = new QueryRequest("TestFolder"); testFolderRequest.setFetch(new Fetch("Name", "Workspace", "Project")); testFolderRequest.setQueryFilter(new QueryFilter("Name", "=", parentFolderName)); testFolderRequest.setWorkspace(WORKSPACE_ID); testFolderRequest.setProject(PROJECT_ID); QueryResponse testFolderQueryResponse = query(testFolderRequest); int folderCount = testFolderQueryResponse.getTotalResultCount(); for (int i = 0; i < folderCount; i++) { String testFolderRef = testFolderQueryResponse.getResults().get(i).getAsJsonObject().get("_ref").getAsString(); JsonObject testFolderObj = testFolderQueryResponse.getResults().get(i).getAsJsonObject(); String pFolder = String.valueOf(testFolderObj.get("Name").getAsString()); if (pFolder.equalsIgnoreCase(parentFolderName)) { //System.out.println("Creating a test case..."); JsonObject newTC = new JsonObject(); newTC.addProperty("Name", testCaseName); newTC.addProperty("Workspace", WORKSPACE_ID); newTC.addProperty("Project", PROJECT_ID); newTC.addProperty("Description", "Selenium Automated TestCase"); newTC.addProperty("TestFolder", testFolderRef); newTC.addProperty("Method", "Automated"); newTC.addProperty("Type", "Functional"); if (!(userID == null)) { newTC.addProperty("Owner", userID); } CreateRequest createRequest = new CreateRequest("testcase", newTC); CreateResponse createResponse = create(createRequest); if (createResponse.wasSuccessful()) { JsonObject tcObj = createResponse.getObject(); tcName = String.valueOf(tcObj.get("Name").getAsString()); logger.info("Created test scenario name is: " + tcName); } else { String[] createErrors; createErrors = createResponse.getErrors(); logger.info("Error while creating test scenario below parent folder!"); for (int j = 0; j < createErrors.length; j++) { System.out.println(createErrors[j]); logger.info(createErrors[j]); } } } } }
Hmmm... I'm not too familiar with the Java REST toolkit, but I can't think of a reason why a larger set of test cases in the workspace would cause the query to fail like that. Did you try checking testCaseQueryResponse.wasSuccessful()? If it returns false, can you see what the error is? testCaseQueryResponse.getErrors() My first thoughts are that you should provide a reasonable value for the limit and pageSize parameters, rather than passing Integer.MAX_VALUE. And second, rather than checking if the returned test cases are in the specified parent folder, you should include a query filter to filter the test cases results on TestFolder.Name = parentFolderName. Then you should only be expecting either 1 or 0 results returned (assuming that you're expecting all test cases within a test folder to have unique names).
Loading using Ion Library returning null JsonObject result
I had built an Android app a few months back, in which one fragment was used to display news using News API. Recently, when I ran the app again, the following error is occurring. I am attaching the code snippet where the error is occurring. Ion.with(getActivity()).load("GET",urltemp).asJsonObject().setCallback(new FutureCallback<JsonObject>() { #Override public void onCompleted(Exception e, JsonObject result) { Log.d(TAG, "enter "); String status = result.get("status").getAsString(); if (status.equals("ok")) { JsonArray array = result.get("articles").getAsJsonArray(); for (int i = 0; i < array.size(); i++) { JsonObject object = array.get(i).getAsJsonObject(); String author = object.get("author").toString(); String title = object.get("title").toString(); title = title.substring(1, title.length() - 1); String url = object.get("url").toString(); url = url.substring(1, url.length() - 1); String urlToImage = object.get("urlToImage").toString(); urlToImage = urlToImage.substring(1, urlToImage.length() - 1); String date = object.get("publishedAt").toString(); String content = object.get("content").toString(); content = content.substring(1, content.length() - 1); items.add(new ModelItems(title, author, date, urlToImage, url)); } adapter = new SlideshowViewModel(getActivity(), items); recyclerView.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); Log.d(TAG, "success"); } else { Log.e(TAG, "error"); } } }); Now, I thought there could be two possible sources of error, either it is a problem with URL(urltemp variable) or it is with Ion library. Now, I pasted the URL in the browser, it is working fine. So, I guess the problem is with Ion. The JsonObject result is null always. Tried different things, but can't figure out any solution. I have never used Postman. So, I am not aware of how to post API response. I am attaching how i assigned URL. A thing I tried is pasting the above URL in the browser. When I paste the URL in browser, I get the following response:
Seems like String status = result.get("status").getAsString(); is being returned null from your server. can you post a API response from postman
Parsin error causing blank screen
enter image description here Hello, I am with a problem that my code does not worked, where the cause of error is(Problem parsing the earthquake JSON results) with this do with my app when executed stay with blank screen. My code be reffers to udacity course about network and the all code can be find on the link below. Please I am begginner in progamming i don't know more what do. (The code what I used) public class QueryUtil { /** * Sample JSON response for a USGS query */ private static final String SAMPLE_JSON_RESPONSE = "{\"type\":\"FeatureCollection\",\"metadata\":{\"generated\":1462295443000,\"url\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10\",\"title\":\"USGS Earthquakes\",\"status\":200,\"api\":\"1.5.2\",\"limit\":10,\"offset\":1,\"count\":10},\"features\":[{\"type\":\"Feature\",\"properties\":{\"mag\":7.2,\"place\":\"88km N of Yelizovo, Russia\",\"time\":1454124312220,\"updated\":1460674294040,\"tz\":720,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us20004vvx\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004vvx&format=geojson\",\"felt\":2,\"cdi\":3.4,\"mmi\":5.82,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":798,\"net\":\"us\",\"code\":\"20004vvx\",\"ids\":\",at00o1qxho,pt16030050,us20004vvx,gcmt20160130032510,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":0.958,\"rms\":1.19,\"gap\":17,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 7.2 - 88km N of Yelizovo, Russia\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[158.5463,53.9776,177]},\"id\":\"us20004vvx\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"94km SSE of Taron, Papua New Guinea\",\"time\":1453777820750,\"updated\":1460156775040,\"tz\":600,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us20004uks\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004uks&format=geojson\",\"felt\":null,\"cdi\":null,\"mmi\":4.1,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":572,\"net\":\"us\",\"code\":\"20004uks\",\"ids\":\",us20004uks,gcmt20160126031023,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":1.537,\"rms\":0.74,\"gap\":25,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.1 - 94km SSE of Taron, Papua New Guinea\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[153.2454,-5.2952,26]},\"id\":\"us20004uks\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.3,\"place\":\"50km NNE of Al Hoceima, Morocco\",\"time\":1453695722730,\"updated\":1460156773040,\"tz\":0,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gy9\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gy9&format=geojson\",\"felt\":117,\"cdi\":7.2,\"mmi\":5.28,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":695,\"net\":\"us\",\"code\":\"10004gy9\",\"ids\":\",us10004gy9,gcmt20160125042203,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":2.201,\"rms\":0.92,\"gap\":20,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.3 - 50km NNE of Al Hoceima, Morocco\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-3.6818,35.6493,12]},\"id\":\"us10004gy9\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":7.1,\"place\":\"86km E of Old Iliamna, Alaska\",\"time\":1453631430230,\"updated\":1460156770040,\"tz\":-540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gqp\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gqp&format=geojson\",\"felt\":1816,\"cdi\":7.2,\"mmi\":6.6,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":1496,\"net\":\"us\",\"code\":\"10004gqp\",\"ids\":\",at00o1gd6r,us10004gqp,ak12496371,gcmt20160124103030,\",\"sources\":\",at,us,ak,gcmt,\",\"types\":\",cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,trump-origin,\",\"nst\":null,\"dmin\":0.72,\"rms\":2.11,\"gap\":19,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 7.1 - 86km E of Old Iliamna, Alaska\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-153.4051,59.6363,129]},\"id\":\"us10004gqp\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.6,\"place\":\"215km SW of Tomatlan, Mexico\",\"time\":1453399617650,\"updated\":1459963829040,\"tz\":-420,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004g4l\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004g4l&format=geojson\",\"felt\":11,\"cdi\":2.7,\"mmi\":3.92,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":673,\"net\":\"us\",\"code\":\"10004g4l\",\"ids\":\",at00o1bebo,pt16021050,us10004g4l,gcmt20160121180659,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":2.413,\"rms\":0.98,\"gap\":74,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.6 - 215km SW of Tomatlan, Mexico\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-106.9337,18.8239,10]},\"id\":\"us10004g4l\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.7,\"place\":\"52km SE of Shizunai, Japan\",\"time\":1452741933640,\"updated\":1459304879040,\"tz\":540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebx\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebx&format=geojson\",\"felt\":51,\"cdi\":5.8,\"mmi\":6.45,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":720,\"net\":\"us\",\"code\":\"10004ebx\",\"ids\":\",us10004ebx,pt16014050,at00o0xauk,gcmt20160114032534,\",\"sources\":\",us,pt,at,gcmt,\",\"types\":\",associate,cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,\",\"nst\":null,\"dmin\":0.281,\"rms\":0.98,\"gap\":22,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.7 - 52km SE of Shizunai, Japan\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[142.781,41.9723,46]},\"id\":\"us10004ebx\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"12km WNW of Charagua, Bolivia\",\"time\":1452741928270,\"updated\":1459304879040,\"tz\":-240,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebw\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebw&format=geojson\",\"felt\":3,\"cdi\":2.2,\"mmi\":2.21,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":573,\"net\":\"us\",\"code\":\"10004ebw\",\"ids\":\",us10004ebw,gcmt20160114032528,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":5.492,\"rms\":1.04,\"gap\":16,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.1 - 12km WNW of Charagua, Bolivia\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-63.3288,-19.7597,582.56]},\"id\":\"us10004ebw\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.2,\"place\":\"74km NW of Rumoi, Japan\",\"time\":1452532083920,\"updated\":1459304875040,\"tz\":540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004djn\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004djn&format=geojson\",\"felt\":8,\"cdi\":3.4,\"mmi\":3.74,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":594,\"net\":\"us\",\"code\":\"10004djn\",\"ids\":\",us10004djn,gcmt20160111170803,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":1.139,\"rms\":0.96,\"gap\":33,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.2 - 74km NW of Rumoi, Japan\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[141.0867,44.4761,238.81]},\"id\":\"us10004djn\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6.5,\"place\":\"227km SE of Sarangani, Philippines\",\"time\":1452530285900,\"updated\":1459304874040,\"tz\":480,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004dj5\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004dj5&format=geojson\",\"felt\":1,\"cdi\":2.7,\"mmi\":7.5,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":1,\"sig\":650,\"net\":\"us\",\"code\":\"10004dj5\",\"ids\":\",at00o0srjp,pt16011050,us10004dj5,gcmt20160111163807,\",\"sources\":\",at,pt,us,gcmt,\",\"types\":\",cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,\",\"nst\":null,\"dmin\":3.144,\"rms\":0.72,\"gap\":22,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.5 - 227km SE of Sarangani, Philippines\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[126.8621,3.8965,13]},\"id\":\"us10004dj5\"},\n" + "{\"type\":\"Feature\",\"properties\":{\"mag\":6,\"place\":\"Pacific-Antarctic Ridge\",\"time\":1451986454620,\"updated\":1459202978040,\"tz\":-540,\"url\":\"http://earthquake.usgs.gov/earthquakes/eventpage/us10004bgk\",\"detail\":\"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004bgk&format=geojson\",\"felt\":0,\"cdi\":1,\"mmi\":0,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"sig\":554,\"net\":\"us\",\"code\":\"10004bgk\",\"ids\":\",us10004bgk,gcmt20160105093415,\",\"sources\":\",us,gcmt,\",\"types\":\",cap,dyfi,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,\",\"nst\":null,\"dmin\":30.75,\"rms\":0.67,\"gap\":71,\"magType\":\"mww\",\"type\":\"earthquake\",\"title\":\"M 6.0 - Pacific-Antarctic Ridge\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-136.2603,-54.2906,10]},\"id\":\"us10004bgk\"}],\"bbox\":[-153.4051,-54.2906,10,158.5463,59.6363,582.56]}"; /** * Create a private constructor because no one should ever create a {#link QueryUtil} object. * This class is only meant to hold static variables and methods, which can be accessed * directly from the class name QueryUtils (and an object instance of QueryUtils is not needed). */ private QueryUtil() { } /** * Return a list of {#link InfosQuake} objects that has been built up from * parsing a JSON response. */ public static ArrayList<InfosQuake> extractEarthquakes() { // Create an empty ArrayList that we can start adding earthquakes to ArrayList<InfosQuake> earthquakes = new ArrayList<>(); // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON // is formatted, a JSONException exception object will be thrown. // Catch the exception so the app doesn't crash, and print the error message to the logs. try { // TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and // build up a list of Earthquake objects with the corresponding data. JSONObject root = new JSONObject(SAMPLE_JSON_RESPONSE); // Getting json array code. JSONArray earthQuakeArrays = root.getJSONArray("Feature"); // Looping through all infosNodes that we want. int i; for (i = 0; i < earthQuakeArrays.length(); i += 1); JSONObject currentEarthQuake = earthQuakeArrays.getJSONObject(i); JSONObject properties = currentEarthQuake.getJSONObject("properties"); String magnitude = properties.getString("mag"); String location = properties.getString("place"); String time = properties.getString("time"); InfosQuake earthquake = new InfosQuake(magnitude, location, time); earthquakes.add(earthquake); } catch (JSONException e) { // If an error is thrown when executing any of the above statements in the "try" block, // catch the exception here, so the app doesn't crash. Print a log message // with the message from the exception. Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); } // Return the list of earthquakes return earthquakes; } } (The error that is causing) Problem parsing the earthquake JSON results org.json.JSONException: No value for Feature at org.json.JSONObject.get(JSONObject.java:389) at org.json.JSONObject.getJSONArray(JSONObject.java:584) at com.example.android.earthquakeapp.QueryUtil.extractEarthquakes(QueryUtil.java:60) at com.example.android.earthquakeapp.EarthquakeActivity.onCreate(EarthquakeActivity.java:20) at android.app.Activity.performCreate(Activity.java:6575) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) at android.app.ActivityThread.access$1000(ActivityThread.java:211) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6946) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) https://classroom.udacity.com/courses/ud843/lessons/1335cf7d-bb4f-48c6-8503-f14b127d2abc/concepts/0eca5789-48d7-4662-8e87-d71490519bd4
You can parse like this below yours did mistake in getting the array using the key features and your didnt loop correctly. public static ArrayList<InfosQuake> extractEarthquakes() { ArrayList<InfosQuake> earthquakes = new ArrayList<>(); try { // TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and // build up a list of Earthquake objects with the corresponding data. JSONObject root = new JSONObject(SAMPLE_JSON_RESPONSE); // Getting json array code. JSONArray earthQuakeArrays = root.optJSONArray("features"); if (earthQuakeArrays == null) { return earthquakes; } // Looping through all infosNodes that we want. for (int i = 0; i < earthQuakeArrays.length(); i++) { JSONObject currentEarthQuake = earthQuakeArrays.optJSONObject(i); if (currentEarthQuake == null) { continue; } JSONObject properties = currentEarthQuake.optJSONObject("properties"); if (properties == null) { // In your case we dont have any other things to get so continue continue; } String magnitude = properties.optString("mag"); String location = properties.optString("place"); String time = properties.optString("time"); InfosQuake earthquake = new InfosQuake(magnitude, location, time); earthquakes.add(earthquake); } } catch (JSONException e) { // If an error is thrown when executing any of the above statements in the "try" block, // catch the exception here, so the app doesn't crash. Print a log message // with the message from the exception. Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); } // Return the list of earthquakes return earthquakes; }
Empty Mysql field (NULL) ends up being a string "null" in Java
I have some data extracted from a MySQL database where some fields are NULL. Not accidentally as a string but properly stored as NULL. When I send these null-data JSON-encoded to my android app, they end up being a string "null" of length 4. So I rebuilt this problem condensed to the essential code: PHP: $string = null; echo $array[0]['alt_names'] = $string; echo json_encode($array); Java: (My PHP class returns a string, in this case jsonResult) Log.i("Tag", "result = " + jsonResult); // result = [{"alt_names":null}] JSONArray jsonArray = new JSONArray(jsonResult); Log.i("Tag", "jsonArray = " + jsonArray); // jsonArray = [{"alt_names":null}] JSONObject jsonObject = new JSONObject(jsonArray.getJSONObject(0).toString()); Log.i("Tag", "jsonobject = " + jsonObject); // jsonobject = {"alt_names":null} String test = jsonObject.get("alt_names").toString(); Log.i("Tag", "test: " + test); // test: null Log.i("Tag", "test.length(): " + test.length()); // test.length(): 4 The missing quotation marks (not) enclosing null in the Log-output show me, that this is not a string "null" butt actually null. Nevertheless the string's length is 4 and this is true: if (test.equals("null")) {Log.i("Tag", "true");} // true What do I not understand? Thanks in advance!
Don't do a toString() on the object return by jsonObject.get("alt_names"). It is actually the static instance of JSONObject.NULL Object test = jsonObject.get("alt_names"); System.out.println(test == JSONObject.NULL); // true System.out.println(test.equals(null)); // true System.out.println(jsonObject.isNull("alt_names")); // true From javadoc : It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value. JSONObject.NULL.equals(null) returns true. JSONObject.NULL.toString() returns "null".
Returning JSON response from Servlet to Javascript/JSP page
I think (actually I KNOW!) I'm doing something wrong here I am trying to populate some values into HashMap and add each hasmap to a list which will be added to a JSON object: JSONObject json = new JSONObject(); try { Map address; List addresses = new ArrayList(); int count = 15; for (int i=0 ; i<count ; i++) { address = new HashMap(); address.put("CustomerName" , "Decepticons" + i); address.put("AccountId" , "1999" + i); address.put("SiteId" , "1888" + i); address.put("Number" , "7" + i); address.put("Building" , "StarScream Skyscraper" + i); address.put("Street" , "Devestator Avenue" + i); address.put("City" , "Megatron City" + i); address.put("ZipCode" , "ZZ00 XX1" + i); address.put("Country" , "CyberTron" + i); addresses.add(address); } json.put("Addresses", addresses); } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(json.toString()); My problem is I know this is returning a string, which I cannot seem to parse (which is the problem). My question is how do I return the actual JSON encoded string (or even should I be doing this?) or what is the best method of attack for this type of problem. The JavaScript I am using for this is below: function getReadyStateHandler(req) { // Return an anonymous function that listens to the // XMLHttpRequest instance return function () { // If the request's status is "complete" if (req.readyState == 4) { // Check that a successful server response was received if (req.status == 200) { msgBox("JSON Response recieved..."); populateDatagrid(req.responseText.toJSON()); } else { // An HTTP problem has occurred alert("HTTP error: " + req.status); } } } } Note the JSON Response comes back fine, but its a string. Any advice is greatly appreciated. I am also opening to using googles Gson, but don't have too much knowledge on that.
Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following: JSONObject json = new JSONObject(); JSONArray addresses = new JSONArray(); JSONObject address; try { int count = 15; for (int i=0 ; i<count ; i++) { address = new JSONObject(); address.put("CustomerName" , "Decepticons" + i); address.put("AccountId" , "1999" + i); address.put("SiteId" , "1888" + i); address.put("Number" , "7" + i); address.put("Building" , "StarScream Skyscraper" + i); address.put("Street" , "Devestator Avenue" + i); address.put("City" , "Megatron City" + i); address.put("ZipCode" , "ZZ00 XX1" + i); address.put("Country" , "CyberTron" + i); addresses.add(address); } json.put("Addresses", addresses); } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(json.toString()); This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
I used JSONObject as shown below in Servlet. JSONObject jsonReturn = new JSONObject(); NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName); map = new HashMap<String, String>(); map.put("Status", "Success"); map.put("FailureReason", "None"); map.put("DataElements", "2"); jsonReturn = new JSONObject(); jsonReturn.accumulate("Header", map); List<String> list = new ArrayList<String>(); list.add(NhAdminTree); list.add(userName); jsonReturn.accumulate("Elements", list); The Servlet returns this JSON object as shown below: response.setContentType("application/json"); response.getWriter().write(jsonReturn.toString()); This Servlet is called from Browser using AngularJs as below $scope.GetNeighborhoodTreeUsingPost = function(){ alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName ); $http({ method: 'POST', url : 'http://localhost:8080/EPortal/xlEPortalService', headers: { 'Content-Type': 'application/json' }, data : { 'action': 64, 'userName' : $scope.userName } }).success(function(data, status, headers, config){ alert("DATA.header.status : " + data.Header.Status); alert("DATA.header.FailureReason : " + data.Header.FailureReason); alert("DATA.header.DataElements : " + data.Header.DataElements); alert("DATA.elements : " + data.Elements); }).error(function(data, status, headers, config) { alert(data + " : " + status + " : " + headers + " : " + config); }); }; This code worked and it is showing correct data in alert dialog box: Data.header.status : Success Data.header.FailureReason : None Data.header.DetailElements : 2 Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct? If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON