itertaing over inputjsonarray - java
import org.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author rajshree.some
*/
public class sample {
public static void main(String[] args) {
// JSONArray arrayinputip = new JSONArray();
// arrayinputip.put("10.253.140.116");
// arrayinputip.put("10.253.140.111");
// arrayinputip.put("10.253.140.118");
// arrayinputip.put("10.253.140.110");
// JSONArray arrayinputusername = new JSONArray();
// arrayinputusername.put("10.253.140.116");
// arrayinputusername.put("10.253.140.111");
// arrayinputusername.put("10.253.140.118");
// arrayinputusername.put("10.253.140.110");
// JSONArray arrayinput = new JSONArray();
// arrayinput.put("10.253.140.116");
// arrayinput.put("10.253.140.111");
// arrayinput.put("10.253.140.118");
// arrayinput.put("10.253.140.110");
JSONObject inputJsonObj1 = new JSONObject();
JSONObject inputJsonObj2 = new JSONObject();
JSONObject inputJsonObj3 = new JSONObject();
JSONArray array= new JSONArray();
try {
inputJsonObj1.put("ipaddress","10.253.140.116");
inputJsonObj1.put("username","bwadmin");
inputJsonObj1.put("password","c0mcast!");
inputJsonObj2.put("ipaddress","10.253.140.117");
inputJsonObj2.put("username","bwadmin");
inputJsonObj2.put("password","bwadmin!");
array.put(inputJsonObj1);
array.put(inputJsonObj2);
// inputJsonObj3.put("server",array);
System.out.println(array);
Client client = Client.create();
WebResource webResource = client.
resource("http://10.85.249.29:8080/checkRest/CheckxARC/getVersion");
ClientResponse response = webResource.type("application/json").
post(ClientResponse.class, array.toString());
String output = response.getEntity(String.class);
System.out.println(" op--->" + output);
} catch (Exception e) {
System.out.println(e.getMessage() + " ");
}
}
}
//This is my clinet code for calling a resftful webservice.
//This is my api
#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
String output3[] = new String[100];
try {
JSONArray inputarray = new JSONArray();
inputarray.put(getVersionJson);
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
for(int i=0;i<inputarray.length();i++){
output3[i]=inputarray.getString(inputarray[i]);
}
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output1;
}
//In my client calling a restful webservice I am sending ipaddress,password,username of two service and I am binding them in an array and calling them.
Now in the calling method I need to access each ipaddress,username and password .But i am not being able to access the ipaddress,username and password.Can u please show me some ways to solve it.
Related
How to remove values from json array?
I have a json file consisting of a single array. the array consists of objects with the keys name, title, pay, age. How can I delete an entire object by the value of the Name key? I am using the "simple json" library, it is quite old, but it suits my purposes. Sorry, there is a lot of code, I don't know what to show. Thank. public class Json { static JSONArray jsonArray; public static void JsonWriter(String filePath, String fullname, String age, String pay, String post) { try { JSONObject worker = new JSONObject(); worker.put("name", fullname); worker.put("age", new Integer(age)); worker.put("post", post); worker.put("pay", new Integer(pay)); jsonArray.add(worker); FileWriter file = new FileWriter(filePath); file.write(jsonArray.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } } //add object public static void AddWorker() throws IOException, ParseException { System.out.println("input name"); String name = handleInput(); System.out.println("input post"); String post = handleInput(); System.out.println("input age"); String age = handleInput(); System.out.println("input pay"); String pay = handleInput(); System.out.println("succes"); JsonWriter("res\\Worker List.json", name, age, pay, post); WorkerList(); } public static void DeleteWorker() { System.out.println(ansi().fg(RED).a("Input name").reset()); String name = handleInput(); } //add object public static void WorkerList() throws IOException, ParseException { Iterator i = jsonArray.iterator(); while (i.hasNext()) { System.out.println(Menu.Separator); JSONObject innearObj = (JSONObject) i.next(); System.out.println("name: " + innearObj.get("name") + lineSeparator() + "age: " + innearObj.get("age") + lineSeparator() + "post: " + innearObj.get("post") + lineSeparator() + "pay: " + innearObj.get("pay")); } System.out.println(Menu.Separator); System.out.println("Add new object?" + lineSeparator() + "0 - Yes" + lineSeparator() + "1 - No"); switch(handleInput()) { case ("0"): AddWorker(); break; } } //Parsing json file public static void WorkersParser(String filePath) { try { JSONParser jsonParser = new JSONParser(); Object obj = jsonParser.parse(new FileReader(filePath)); jsonArray = (JSONArray) obj; WorkerList(); } catch (IOException | ParseException e) { e.printStackTrace(); } } } public static String handleInput() { try { String input; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); input = reader.readLine(); return input; } catch (Exception ignored) { } return ""; } //// [ { "post":"post1", "name":"name1", "pay":1, "age":1 }, { "post":"post2", "name":"name2", //if name = "post2", delete // { "pay":2, // "post":"post2", "age":2 // "name":"name2", } // "pay":"2", ] // "age":2 // }
You can loop all of them, check for that parameter and remove() by the index: String jsonString = "[{\"post\":\"post1\",\"name\":\"name1\",\"pay\":1,\"age\":1},{\"post\":\"post2\",\"name\":\"name2\",\"pay\":2,\"age\":2}]"; JSONArray arr = new JSONArray(jsonString); String wordToDeleteBy = "name1"; System.out.println(arr.length()); //prints 2 for (int i = 0; i<arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); if (obj.has("name") && obj.get("name").equals(wordToDeleteBy)) { arr.remove(i); } } System.out.println(arr.length()); //prints 1
Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
An error occurs when searching for a name using the application thus showing no results when searching for a name within the app. Tried changing between JSONArray and JSONObject but a similar error occurs. The URL is correct and does show the data in JSON format. package com.rjassi.service; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import javax.net.ssl.HttpsURLConnection; public class CharacterSearchService extends AbstractService { private String query; private JSONObject results; private JSONObject jsonObject; public CharacterSearchService(String query) { try { this.query = URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } } public JSONObject getResults() { return results; } //This method will run on a separate thread to the UI #Override public void run() { URL url; boolean error = false; HttpsURLConnection httpsURLConnection = null; StringBuilder result = new StringBuilder(); try { url = new URL("https://www.moogleapi.com/api/v1/characters/search?name=" + query); httpsURLConnection = (HttpsURLConnection) url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line); } //put the result string into a JSONObject JSONArray jsonArray = jsonObject.getJSONArray("name"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) { error = true; } else { results = jsonObject; } } /* If the JSONObject has a "Response" attribute and it equals false then no results were found if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) { error = true; } else { results = jsonObject.getJSONArray("Search"); } */ } catch (Exception ex) { ex.printStackTrace(); results = null; error = true; } finally { if (httpsURLConnection != null) { httpsURLConnection.disconnect(); } } /* Call the serviceCallComplete() method in the super class; AbstractService which will then inform the listeners that the search is complete */ super.serviceCallComplete(error); } } public void serviceComplete(AbstractService abstractService) { if (!abstractService.hasError()) { //Cast the AbstractService object passed into the method to a CharacterSearchService object CharacterSearchService characterSearchService = (CharacterSearchService) abstractService; //Create a string array that is the same as the results JSONArray String[] result = new String[characterSearchService.getResults().length()]; //searchResults.clear(); /* Loops through the JSONArray and get the name of each JSONObject it contains. Store each name in string array. */ for (int i = 0; i < characterSearchService.getResults().length(); i++) { try { //Store each character result as a JSONObject in the ArrayList //searchResults.add(characterSearchService.getResults().getJSONObject(i)); android.util.Log.i("sdfsf", characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name")); result[i] = characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name"); } catch (JSONException ex) { result[i] = "error"; } } //Display the string array on screen in the ListView. setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result)); } else{ String[] result = new String[]{"No Results"}; setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result)); } } This is the error which occurs after searching for a name: W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference at com.rjassi.service.CharacterSearchService.run(CharacterSearchService.java:53) at java.lang.Thread.run(Thread.java:764) The expected output should show the name which is searched by returning that name or similar ones from the search results of the API.
jsonObject is never initialized so it will throw a NullPointerException when you try to dereference it. Initialize the JSONObject with your server response data. If your response string is properly formatted JSON, you can initialize the JSONObject using the following constructor: JSONObject Added in API level 1 public JSONObject (String json) Creates a new JSONObject with name/value mappings from the JSON string. //put the result string into a JSONObject JSONArray jsonArray = jsonObject.getJSONArray("name"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) { error = true; } else { results = jsonObject; } }
Getting this error while parsing data in JSON format in android
I'm getting this error: org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONObject public class QueryUtils { private QueryUtils(){ } //private static final String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10"; public static ArrayList<Earthquake> extractEarthquakes() { String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10"; ArrayList<Earthquake> earthquakes = new ArrayList<Earthquake>(); try { String responseDate = URL.toString(); JSONObject rootObject = new JSONObject(responseDate); JSONArray features = rootObject.getJSONArray("features"); // Date dateObject; // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM DD,yyyy h:mm a", Locale.ENGLISH); //iterate through loop to display each value for(int i=0; i <features.length(); i++){ JSONObject jsonObjectForDetails = features.getJSONObject(i); JSONObject jsonObjectForProperties = jsonObjectForDetails.getJSONObject("properties"); // double magValue = double.parseInt(jsonObjectForProperties.optString("mag").toString()); // String addressDetails = jsonObjectForProperties.optString("place").toString(); // int dateDetails = Integer.parseInt(jsonObjectForProperties.optString("time").toString()); double magValue = jsonObjectForProperties.getDouble("mag"); String addressDetails = jsonObjectForProperties.getString("place"); long dateDetails = jsonObjectForProperties.getLong("time"); // dateObject = new Date(dateDetails); // long dateToDisplay = simpleDateFormat.format(dateObject); earthquakes.add(new Earthquake(magValue,addressDetails,dateDetails)); } } catch (JSONException e) { Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); } return earthquakes; } }
to summarize the other comments: to retrieve data from url use this function: public static String getJsonFromServer(String url) throws IOException { BufferedReader inputStream = null; URL jsonUrl = new URL(url); URLConnection dc = jsonUrl.openConnection(); dc.setConnectTimeout(5000); dc.setReadTimeout(5000); inputStream = new BufferedReader(new InputStreamReader( dc.getInputStream())); // read the JSON results into a string String jsonResult = inputStream.readLine(); return jsonResult; } for your case use try { String responseDate= getJsonFromServer(URL); //the other code: } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } instead of String responseDate = URL.toString(); and this code (for json parsing) works too: import org.json.JSONArray; import org.json.JSONObject; public class EarthQuakeTest { //http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10 private static final String str = "{\"type\":\"FeatureCollection\",\"metadata\":{\"generated\":1475336259000,\"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\":1463685050282,\"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\":\",gcmt20160130032510,at00o1qxho,pt16030050,us20004vvx,gcmt20160130032512,\",\"sources\":\",gcmt,at,pt,us,gcmt,\",\"types\":\",associate,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"94km SSE of Taron, Papua New Guinea\",\"time\":1453777820750,\"updated\":1466450055338,\"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\":\",gcmt20160126031023,us20004uks,gcmt20160126031020,\",\"sources\":\",gcmt,us,gcmt,\",\"types\":\",associate,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.3,\"place\":\"50km NNE of Al Hoceima, Morocco\",\"time\":1453695722730,\"updated\":1466450270946,\"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\":\",gcmt20160125042203,us10004gy9,gcmt20160125042202,\",\"sources\":\",gcmt,us,gcmt,\",\"types\":\",associate,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":7.1,\"place\":\"86km E of Old Iliamna, Alaska\",\"time\":1453631430230,\"updated\":1469293028539,\"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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.6,\"place\":\"215km SW of Tomatlan, Mexico\",\"time\":1453399617650,\"updated\":1466450324948,\"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\":\",gcmt20160121180659,at00o1bebo,pt16021050,us10004g4l,gcmt20160121180657,\",\"sources\":\",gcmt,at,pt,us,gcmt,\",\"types\":\",associate,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.7,\"place\":\"52km SE of Shizunai, Japan\",\"time\":1452741933640,\"updated\":1466450357311,\"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,gcmt20160114032534,pt16014050,at00o0xauk,gcmt20160114032533,\",\"sources\":\",us,gcmt,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.1,\"place\":\"12km WNW of Charagua, Bolivia\",\"time\":1452741928270,\"updated\":1463165886000,\"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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.2,\"place\":\"74km NW of Rumoi, Japan\",\"time\":1452532083920,\"updated\":1463165873000,\"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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6.5,\"place\":\"227km SE of Sarangani, Philippines\",\"time\":1452530285900,\"updated\":1466450384901,\"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\":\",gcmt20160111163807,at00o0srjp,pt16011050,us10004dj5,gcmt20160111163805,\",\"sources\":\",gcmt,at,pt,us,gcmt,\",\"types\":\",associate,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\"},\r\n{\"type\":\"Feature\",\"properties\":{\"mag\":6,\"place\":\"Pacific-Antarctic Ridge\",\"time\":1451986454620,\"updated\":1466450408406,\"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\":\",gcmt20160105093415,us10004bgk,gcmt20160105093414,\",\"sources\":\",gcmt,us,gcmt,\",\"types\":\",associate,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]}"; public static void main(String[] args) { // TODO Auto-generated method stub JSONObject rootObject = new JSONObject(str); JSONArray features = rootObject.getJSONArray("features"); for(int i=0; i <features.length(); i++){ JSONObject jsonObjectForDetails = features.getJSONObject(i); JSONObject jsonObjectForProperties = jsonObjectForDetails.getJSONObject("properties"); double magValue = jsonObjectForProperties.getDouble("mag"); String addressDetails = jsonObjectForProperties.getString("place"); long dateDetails = jsonObjectForProperties.getLong("time"); // dateObject = new Date(dateDetails); // long dateToDisplay = simpleDateFormat.format(dateObject); // earthquakes.add(new Earthquake(magValue,addressDetails,dateDetails)); System.out.println(magValue + " " + addressDetails + " " + dateDetails); } System.out.println(rootObject.hashCode()); } }
No value for "Invoice"
Anyone knows what might be the reason why my "invoice" does not have an value? Tallied with the php response , it is called invoice. At this line String invoice = jtransaction.getString("invoice"); public static ArrayList<Transaction> getMemberTransactions(String memberId) { String url= second_URL + "get_member_transactions.php"; String method = GET; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("member_id", memberId)); JSONObject result = makeHttpRequest(url, method, params); try { if (result.getInt("success") == 1) { ArrayList<Transaction> list = new ArrayList<Transaction>(); JSONArray jItems = result.getJSONArray("transaction_info"); int count = jItems.length(); for (int i = 0; i < count; i++) { JSONObject jtransaction = jItems.getJSONObject(i); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US); Date date = null; try { date = sdf.parse(jtransaction.getString("date")); } catch (ParseException e) { e.printStackTrace(); } String invoice = jtransaction.getString("invoice"); String warehouse = jtransaction.getString("warehouse"); Transaction transaction = new Transaction(date,invoice, warehouse); list.add(transaction); } return list; } } catch (JSONException e) { e.printStackTrace(); } return null; } php while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { $transactionInfo[]["date"] = get_date($row['Transaction_Date']); $transactionInfo[]["invoice"] = $row['Invoice_No']; $transactionInfo[]["warehouse"] = $row['WarehouseName']; } if(!empty($transactionInfo)===true) { response_success($transactionInfo); } function response_success($transactionInfo) { $response = array(); $response["success"] = 1; $response["transaction_info"] = $transactionInfo; echo json_encode($response); exit; }
This: $transactionInfo[]["date"] = get_date($row['Transaction_Date']); $transactionInfo[]["invoice"] = $row['Invoice_No']; $transactionInfo[]["warehouse"] = $row['WarehouseName']; will create three separate items in $transactionInfo, one containing date, one with invoice and one with warehouse. Example: array(3) { [0]=> array(1) { ["date"]=> string(10) "2014-10-20" } [1]=> array(1) { ["invoice"]=> string(5) "08/15" } [2]=> array(1) { ["warehouse"]=> int(13) } } I suppose you want them in one item, so you have to build it like this: $item["date"] = get_date($row['Transaction_Date']); $item["invoice"] = $row['Invoice_No']; $item["warehouse"] = $row['WarehouseName']; // now add the item to the array $transactionInfo[] = $item; Example: array(1) { [0]=> array(3) { ["date"]=> string(10) "2014-10-20" ["invoice"]=> string(5) "08/15" ["warehouse"]=> int(13) } }
Searching Twitter with OAuth
Okay so I get an access token for Twitter each time I run my program...(It's tedious at the moment but I will find out how to make it a persistent store)... How do I go about using this access token so that when I search, I won't get a "Rate limit exceeded. Clients may not make more than 150 requests per hour." error? It happens when I'm searching for the following: "https://api.twitter.com/1/users/show.json?screen_name=[screenName]" Which is coded as : BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream())); In my code below: public class UDC { private static String term1; private static String term2; public static String PIN; private static final String twitterSearch = "http://search.twitter.com/search.json?q=%23"; private static String rppPage = "&rpp=500&page=1"; private static final String ffGet = "https://api.twitter.com/1/users/show.json?screen_name="; private static final String CONSUMER_KEY = "K7el7Fqu7UtcJv3A3ssOQ"; private static final String CONSUMER_SECRET = "w7ZX27ys58mafLYeivuA2POVe0gjhTIIUH26f2IM"; private static String entities = "&include_entities=true"; static Object[][] tableData = new Object[500][6]; static SearchResultC s = new SearchResultC(); static StringBuffer buff = new StringBuffer(); static StringBuffer buff1 = new StringBuffer(); public static void main (String args[]) throws Exception{ verifyURL v = new verifyURL(); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; // = loadAccessToken(Integer.parseInt(args[0])); //Twitter twitter = factory.getInstance); //twitter.setOAuthConsumerKey(COMSUMER_KEY, COMSUMER_SECRET); //twitter.setOAuthAccessToken(accessToken); v.valURLText.setText(requestToken.getAuthorizationURL()); v.vFrame.setVisible(true); int p = 0; do { //nothing } while (v.vFrame.isVisible()); try { if (PIN.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, PIN); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if(401 == te.getStatusCode()) { showErrorPane("Unable to get access code", "Error"); p = 1; } else { te.printStackTrace(); } } //storeAccessToken(twitter.verifyCredentials().getId(), accessToken); if (p == 0) { initComponents(); UDTFrame.setVisible(true); } else { System.exit(0); } } #SuppressWarnings({ "static-access"}) private static void searchButtonMouseClicked(String t1, String t2) throws IOException { if(t1.equals("") || t2.equals("") || t1.equals(t2)) { showErrorPane("Invalid Search Terms", "Search Error"); } else { s.getInitComponents(); clicked(t1, 0); clicked(t2, 3); s.SRTFrame.setVisible(true); s.sTerm1Field.setText(t1); s.sTerm2Field.setText(t2); } } #SuppressWarnings("static-access") public static void clicked(String term, int t){ UDTFrame.setVisible(false); float follower; float friends; float ffRatio; float DUA; int statuses; int day; int year; String month; try { URL searchURL1 = new URL (twitterSearch + term + rppPage); //String searchURL = new String (twitterSearch + term + rppPage); BufferedReader br = new BufferedReader( new InputStreamReader(searchURL1.openConnection().getInputStream())); //OAuthRequest request = new OAuthRequest(Verb.POST, searchURL); int c; while ((c=br.read()) != -1) { buff.append((char)c); } br.close(); /*******************************************************************************************/ /*******************************************************************************************/ /******************************** follower/friend ratio ************************************/ /*******************************************************************************************/ /*******************************************************************************************/ JSONObject js = new JSONObject(buff.toString()); JSONArray tweets = js.getJSONArray("results"); JSONObject tweet = new JSONObject(); for(int i=0; i < tweets.length(); i++) { tweet = tweets.getJSONObject(i); //System.out.println(tweet); //user[i] = tweet.getString("from_user_name"); //System.out.println(tweet.getString("from_user_name")); //System.out.println(user[i]); String userName = tweet.getString("from_user"); //URL ffUser = new URL(ffGet + user[i] + entities); URL ffUser = new URL(ffGet + userName + entities); String ffUser1 = new String(ffGet + userName + entities); BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream())); OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1); int d, e = 0; while((d = ff.read()) != -1) { buff1.append((char)d); e++; } ff.close(); JSONObject js1 = new JSONObject(buff1.toString()); //System.out.println(js1); //JSONArray userData = new JSONArray(buff1.toString()); //JSONObject userData1; //for(int j = 0; j < js1.length(); i++){ //userData1 = userData.getJSONObject(j); follower = js1.getInt("followers_count"); friends = js1.getInt("friends_count"); ffRatio = friends/follower; String createdDate = js1.getString("created_at"); statuses = js1.getInt("statuses_count"); String nameData = js1.getString("name"); String gen = gender(nameData); //} } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I'm completely new to this OAuth and Access Tokens and all so any help will be much appreciated.
With OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1); you are doing an unauthenticated request using the Scribe library (you never instantiated an OAuthService object which would have to be used to sign this request). So when you do this too often Twitter denies these requests. So your problem here does indeed come from mixing Twitter4J and Scribe.