I want to extract
the val from the first array
SVCNO and PATH from the second array
PROBLEM: However, I cannot seem to extract anything due to this error:
This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.
These are my codes:
//where URL4 = http://www.onemap.sg/BusServiceAPI/Service1.svc/showRoute?token=489ce5de815c81c7fda85af3980e9b6258124ca68837e425a2b7373c2d869bbf9ea4ad5a4901fbce20da45b4e095643b&svc=39%7C1%3B85%7C1%3B169%7C1%3B811%7C1%3B851%7C1%3B852%7C1%3B854%7C1%3B854E%7C1%3B858%7C1%3B965%7C1%3B969%7C1
List<NameValuePair> URLparams4 = new LinkedList<NameValuePair();
URLparams4.add(new BasicNameValuePair(PARAM_TOKEN, TOKEN));
URLparams4.add(new BasicNameValuePair(PARAM_SVC, joinBusDirAndSvc));
String paramString4 = URLEncodedUtils.format(URLparams4,"utf-8");
String url4 = BusShowRoute_URL + paramString4;
ResponseHandler<String>handler4 = new BasicResponseHandler();
HttpGet get4 = new HttpGet(url4);
HttpParams httpParameters4 = new BasicHttpParams();
DefaultHttpClient client4 = new DefaultHttpClient (httpParameters4);
try
{
String response4 = client4.execute(get4,handler4);
System.out.println("busesponse4= " + response4); //response array
//convert result page into JSON Object
JSONObject jsonResponse4= new JSONObject(response4);
//get JSON Array
jsArray_busRoute = jsonResponse4.getJSONArray(ATTR_BUSROUTE);
System.out.print("jsArray_busRoute== " + jsArray_busRoute);
for (int i = 0; i < jsArray_busRoute.length(); i++)
{
JSONObject obj_busRoute = jsArray_busRoute.getJSONObject(i);
if (!obj_busRoute.has(ATTR_PAGECOUNT))
{
String val = obj_busRoute.getString(ATTR_VAL + i);
System.out.print("val== " + val);
}
}
}
Below is the JSON response:
{
"BusRoute":
{
"PageCount":[
{
"Val0":"TAMPINES INT,
YISHUN TEMP INT"
},
{
"Val1":"PUNGGOL TEMP INT,
YISHUN TEMP INT"
}
],
"1":[
{
"SVCNO":"39",
"DRC":"1",
"SQNO":"1",
"DST":"0",
"SBS":"75009",
"EBS":"76059",
"PATH":"40287.2481620079,37450.8849868048;
40298.2076238208,37458.4535869379;
40309.8456332916,37470.8674859032;
40320.7077835361,37487.9365402292;
40326.1859934768,37512.3384070937;
40255.2463979153,37512.7719051559;
}
]
}
}
Thank you for helping!
Related
Below I have my code for a search request. As yelp only allows to get only 50 results I have a problem to make it work.
So basically offset = 0 and limit = 50 will bring me the results 0-50
offset = 50 and limit = 50 will bring me the results 51-100
So and in my case I need 1000 Results. How can I manage it? I tried everything in my power and now I need some help.
public class Search2 {
static HttpURLConnection conn;
public static void Searche() {
int offset = 0;
int limit = 50;
try {
for (int i = 0; i < 950; i=+50) {
URL url = new URL("https://api.yelp.com/v3/businesses/search?location=" + gui.Lead_1.tFOrt.getText()
+ "&categories=" + gui.Lead_1.tFKeyword.getText() + "&offset=" + i + "&limit=50");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
}
try {
conn.setRequestProperty("Authorization", "Bearer " + dbb.Pfad.getPath() + " ");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// throwing the error message if the response is not available.
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
// capturing the response and appending it to the response string.
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuffer response = new StringBuffer();
while ((output = br.readLine()) != null) {
response.append(output);
}
// converting the response to the JSONObject.
JSONObject jsonObj = new JSONObject(response.toString());
JSONArray list1 = new JSONArray();
JSONArray arr = jsonObj.getJSONArray("businesses");
JSONObject details = new JSONObject();
// capturing the specific values(name, rating, reviewcount) from the response
for (int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
int rating = arr.getJSONObject(i).getInt("rating");
int review_count = arr.getJSONObject(i).getInt("review_count");
JSONObject address = arr.getJSONObject(i).getJSONObject("location");
details.put("Name", name);
details.put("Rating", rating);
details.put("Review Count", review_count);
details.put("Address", address);
JSONObject object = new JSONObject();
object.put("restaurant " + (i + 1), details);
list1.put(object);
Lead_2.row[0]=i+1;
Lead_2.row[1]=arr.getJSONObject(i).getString("name");
Lead_2.row[2]=arr.getJSONObject(i).getJSONObject("location").getString("address1");
Lead_2.model.addRow(Lead_2.row);
}
I'm trying to modify the TestSets property of a TestCase.
JsonArray newTestSets = new JsonArray();
... add values as needed ( in the simplest case I'm clearing the property )
JsonObject updates = new JsonObject();
updates.add("TestSets", newTestSets);
I create the updateRequest like I do for all other updates
UpdateRequest updateRequest = new UpdateRequest(ref, updates)
I don't get any error but nothing has changed. The TestCase is still in several TestSets
What am I missing?
I verified that it works to update TestSets collection on a TestCase. See this github repo.
public class UpdateTestSetsOnTestCase {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String workspaceRef = "/workspace/12352608129";
String applicationName = "RestExample_updateTestSetsOnTC";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
try {
String setID = "TS24";
String testid = "TC3";
QueryRequest tsRequest = new QueryRequest("TestSet");
tsRequest.setWorkspace(workspaceRef);
tsRequest.setQueryFilter(new QueryFilter("FormattedID", "=", setID));
QueryResponse tsQueryResponse = restApi.query(tsRequest);
if(tsQueryResponse.getTotalResultCount() == 0){
System.out.println("Cannot find tag: " + setID);
return;
}
JsonObject tsJsonObject = tsQueryResponse.getResults().get(0).getAsJsonObject();
String tsRef = tsJsonObject.get("_ref").getAsString();
System.out.println(tsRef);
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setWorkspace(workspaceRef);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "TestSets"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testid));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);;
if (testCaseQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test case : " + testid);
return;
}
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
System.out.println(testCaseRef);
int numberOfTestSets = testCaseJsonObject.getAsJsonObject("TestSets").get("Count").getAsInt();
System.out.println(numberOfTestSets + " testset(s) on " + testid);
QueryRequest testsetCollectionRequest = new QueryRequest(testCaseJsonObject.getAsJsonObject("TestSets"));
testsetCollectionRequest.setFetch(new Fetch("FormattedID"));
JsonArray testsets = restApi.query(testsetCollectionRequest).getResults();
for (int j=0;j<numberOfTestSets;j++){
System.out.println("FormattedID: " + testsets.get(j).getAsJsonObject().get("FormattedID"));
}
testsets.add(tsJsonObject);
JsonObject testCaseUpdate = new JsonObject();
testCaseUpdate.add("TestSets", testsets);
UpdateRequest updateTestCaseRequest = new UpdateRequest(testCaseRef,testCaseUpdate);
UpdateResponse updateTestCaseResponse = restApi.update(updateTestCaseRequest);
if (updateTestCaseResponse.wasSuccessful()) {
QueryRequest testsetCollectionRequest2 = new QueryRequest(testCaseJsonObject.getAsJsonObject("TestSets"));
testsetCollectionRequest2.setFetch(new Fetch("FormattedID"));
JsonArray testsetsAfterUpdate = restApi.query(testsetCollectionRequest2).getResults();
int numberOfTestSetsAfterUpdate = restApi.query(testsetCollectionRequest2).getResults().size();
System.out.println("Successfully updated : " + testid + " TestSets after update: " + numberOfTestSetsAfterUpdate);
for (int j=0;j<numberOfTestSetsAfterUpdate;j++){
System.out.println("FormattedID: " + testsetsAfterUpdate.get(j).getAsJsonObject().get("FormattedID"));
}
}
} finally {
restApi.close();
}
}
}
I'm currently working on a project that requires the latitude and longitude of a given address (input). Google maps API returns in json format, and I've done research and found that json-simple is the best option for my project. I have this code as well as the String output from google maps API, and would highly appreciate some help in parsing properly.
Also note: the call: MapTile.receiveJson just returns the string from google's API (linked below)
try {
String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonAdr);
System.out.println("lat=" + json.get("address_components"));
} catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}
This is the exact string output from google's API:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
I realize I could do String parsing, however it would be inefficient as I will be using more of google's API. I have also viewed other stack overflow, as well as their JSON website but found no examples with multiple JSON arrays such as those returned by google.
Any help is greatly appreciated.
Here's the solution:
I basically made a stand alone and I parsed your JSON like this:
First : This is the method I used to parse the JSON:
public String loadJSON(String someURL) {
String json = null;
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(someURL);
try {
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
StatusLine statusline = mHttpResponse.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode != 200) {
return null;
}
InputStream jsonStream = mHttpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = builder.toString();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
mHttpClient.getConnectionManager().shutdown();
return json;
}
Second : Used Async Task to download the data:
public class BackTask extends AsyncTask<Void, Void, Void> {
String url;
public BackTask(String URL) {
super();
this.url = URL;
}
#Override
protected Void doInBackground(Void... params) {
getData(url);
return null;
}
}
Third: Method to get the data and parse it. I have made some comments for this part since it's a bit long than usual.
public void getData(String URL) {
try {
JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
// Log.d("JSON Data : ", mainJsonObject.toString());
String Status = mainJsonObject.getString("status");
Log.d("JSON Status : ", Status + "\n" + "---------------------");
JSONArray mainArray = mainJsonObject.getJSONArray("results");
// Log.d("JSON Array : ", mainArray.toString());
for (int i = 0; i < mainArray.length(); i++) {
JSONObject insideJsonObject = mainArray.getJSONObject(i);
if (insideJsonObject != null) {
String address_components = insideJsonObject
.getString("address_components");
// Log.d("Inside JSON Array : ", address_components);
JSONArray addressJSON = insideJsonObject
.getJSONArray("address_components");
// Log.d("Inside JSON ADDress : ", addressJSON.toString());
String formatted_address = insideJsonObject
.getString("formatted_address");
Log.d("Inside JSON formatted_address : ", formatted_address
+ "\n" + "-----------");
for (int ji = 0; ji < mainArray.length(); ji++) {
JSONObject geoMetryJO = mainArray.getJSONObject(ji);
if (geoMetryJO != null) {
JSONObject geometry = geoMetryJO
.getJSONObject("geometry");
// Log.d("Inside JSON geometry : ",
// geometry.toString()+"\n"+"----------");
String location_type = geometry
.getString("location_type");
Log.d("Inside JSON location_type : ", location_type
+ "\n" + "------------");
JSONObject locationJSONObject = geometry
.getJSONObject("location");
String Latitude = locationJSONObject
.getString("lat");
Log.d("Inside JSON Latitude : ", Latitude + "\n"
+ "--------------");
String Longitude = locationJSONObject
.getString("lng");
Log.d("Inside JSON Longitude : ", Longitude + "\n"
+ "------------");
JSONObject viewportJSONObject = geometry
.getJSONObject("viewport");
// Log.d("Inside JSON viewportJSONObject : ",
// viewportJSONObject.toString()+"\n"+"------------");
JSONObject northeastJSONObject = viewportJSONObject
.getJSONObject("northeast");
String Lat = northeastJSONObject.getString("lat");
Log.d("Inside JSON Lat : ", Lat + "\n"
+ "------------");
String Lon = northeastJSONObject.getString("lng");
Log.d("Inside JSON Lon : ", Lon + "\n"
+ "------------");
JSONObject southwestJSONObject = viewportJSONObject
.getJSONObject("southwest");
String south_Lat = southwestJSONObject
.getString("lat");
Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
+ "------------");
String south_Lon = southwestJSONObject
.getString("lng");
Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
+ "------------");
}
}
for (int k = 0; k < addressJSON.length(); k++) {
JSONObject addressJSONObject = addressJSON
.getJSONObject(k);
if (addressJSONObject != null) {
String long_name = addressJSONObject
.getString("long_name");
Log.d("Inside JSON LongName : ", long_name);
String short_name = addressJSONObject
.getString("short_name");
Log.d("Inside JSON ShortName : ", short_name);
JSONArray addressJSONArray = addressJSONObject
.getJSONArray("types");
Log.d("Inside JSON JSONADD : ",
addressJSONArray.toString() + "\n"
+ "-------------");
}
}
JSONArray insideJsonArray = insideJsonObject
.getJSONArray("types");
Log.d("Inside JSON Types : ", insideJsonArray.toString());
String street = insideJsonObject.getString("types");
Log.d("Inside JSON Street : ", street);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After getting all the data, you can use it in anyway you want cause it's mostly in the string format. You can just copy and paste this method and it should run fine.
Fourth : On the onCreate() method, just executed the task like this:
public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackTask(URL).execute();
}
This was the complete solution for this question. Let me know if have any questions for this. Hope this helps..Good Luck.. :)
I did this for formatted_address. I type casted explicitly here. But getJSONArray () and getJSONObject() methods will perform the typecasting too.
// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++)
System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.
how can i read this JSON format,and user can pass the from and to into URL,
and want to print these from_amount and to_amount into the text view on button click.
api url
{
"from": "INR",
"to": "GBP",
"from_amount": 2,
"to_amount": 0.019798718798321
}
i tried to do the snippet below.,but it is not returning any thing and also not giving any error in thr log cat
private static final String API_URL = "http://devel.farebookings.com/api/curconversor/t1/t2/usds/json";
if (!usdValue.getText().toString().equals("")) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(API_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject ratesObject = jsonObj
.getJSONObject("from");
JSONObject ratessObject = jsonObj
.getJSONObject("to");
JSONObject rates2Object = jsonObj
.getJSONObject("from_amount");
//Double RateTo = Double.valueOf(t2
// .toString());
Double RateFrom = Double.valueOf(t1
.toString());
// Double RateFrom = ratesObject.getDouble("from");
//Double RateTo = ratesObject.getDouble(t2.toString());
//Log.i("CHACHING", "GBP: " + gbpRate);
//Log.i("CHACHING", "EUR: " + eurRate);
Double usds = Double.valueOf(usdValue.getText()
.toString());
//Double gbps = usds * RateFrom;
// Double euros = usds * RateTo;
//Result.setText("ConvertedFrom: "
// + String.valueOf(RateFrom)+ "ConvertedTo: "
// + String.valueOf(RateTo));
Toast.makeText(getApplicationContext(),
Result.getText().toString(), Toast.LENGTH_LONG)
.show();
//ConvertedTo.setText("ConvertedTo: "
//+ String.valueOf(RateTo));
}
Don't use the getJsonObject() method to get the values inside the JSONObject, but use the corresponding getters for the types of the values. The key-value pairs themselves are no JSONObjects.
JSONObject jsonObj = new JSONObject(response);
String fromCurrency = jsonObj.getString("from");
String toCurrency= jsonObj.getJSONObject("to");
Double fromAmount = jsonObj.getDouble("from_amount");
Double toAmount= jsonObj.getDouble("to_amount");
public static VehicleDetails[] getAllVehicles(String clientCode,String secretCode) throws ClientProtocolException,
IOException, JSONException {
VehicleDetails[] vd = null;
String result = null;
VehicleDetails vdetails = null;
ArrayList<VehicleDetails> vehicleArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
String loginUrl = "getAllVehicles";
try {
HttpPost request = new HttpPost(URL + loginUrl);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("clientCode", clientCode));
postParameters.add(new BasicNameValuePair("secretCode", secretCode));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(entity);
HttpResponse response = getThreadSafeClient().execute(request);
entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
Log.d(TAG, "result>>" + result);
JSONObject object = (JSONObject) new JSONTokener(result)
.nextValue();
VehicleDetails.status_login = object.getString("message");
if (VehicleDetails.status_login.contentEquals("success")) {
JSONArray array = object.getJSONArray("data");
vehicleArrayList.clear();
for (int i = 0; i < array.length(); i++) {
Log.d(TAG, "LiveTracking>>>>>>>>>>>");
JSONObject jObj = array.getJSONObject(i);
String vehicleId = jObj.getString("vehicle_id").toString();
String vehicleNumber = jObj.getString("vehicle_number").toString();
vdetails = new VehicleDetails();
vdetails.vehicleId = vehicleId;
vdetails.vehicleNo = vehicleNumber;
vehicleArrayList.add(vdetails);
}
vd = new VehicleDetails[vehicleArrayList.size()];
for (int x = 0; x < vehicleArrayList.size(); ++x) {
vd[x] = (VehicleDetails) vehicleArrayList.get(x);
}
} else if(VehicleDetails.status_login.contentEquals("failed")){
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jObj = array.getJSONObject(i);
vdetails.failReason = jObj.getString("data").toString();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return vd;
}
Hi,
Value from the webservice is repeating when it is added to the arraylist.I clear the arraylist.But the issue still exixts.
My json response from webservice is:
{
"message": "success",
"data": [
{
"vehicle_id": "7",
"vehicle_number": "KL-01 BA 2233"
},
{
"vehicle_id": "2",
"vehicle_number": "KL 01 AP 9650"
},
{
"vehicle_id": "10",
"vehicle_number": "KL 01 AP 9650 N"
},
{
"vehicle_id": "9",
"vehicle_number": "HB"
}
]
}
HB is repeating four times when added to arraylist
Please help me?
Please suggest a method to solve this?
your problem is that your recreating a single instance and because java is pass by reference all your values in arraylist point at the last instance.
to prevent this problem for each entry create a new instance;
VehicleDetails vdetails = new VehicleDetails();
vdetails.vehicleId = vehicleId;
vdetails.vehicleNo = vehicleNumber;
vehicleArrayList.add(vdetails);
and delete this line
VehicleDetails vdetails = null;