Reputation: 5
I have a URL. In it there is a straightforward JSON array in this format:
["england","france","germany","america","denmark","italy","greece","portugal","poland"]
All I need to do is read this from the Java, and put it into an ArrayList
.
It sounded so simple, but I've been on it for hours.
This is what I've done so far:
package com.example.landmarksapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Fetches JSON results and returns into correct format for the GUI
* @author Alicia
*
*/
public class Conector {
private String urlToCities = "http://jagdeep.co:8080/LandmarkServers-0.1/city/listJSON/";
/**
* Fetches list of cities
* @param urlToCities the link to the JOSN file with the list of cities
* @return ArrayList<String> of cities
* @throws IOException
* @throws JSONException
*/
public List<String> fetchCities(String urlToCities) throws IOException, JSONException {
List<String> result = new ArrayList();
JSONObject jsonResults = readJsonFromUrl(urlToCities);
return result;
}
/**
* @inheritDoc
*/
public List<String> fetchCities() throws IOException, JSONException {
return fetchCities(urlToCities);
}
/**
*
* @param rd
* @return
* @throws IOException
*/
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
System.out.println(cp);
}
return sb.toString();
}
/**
*
* @param url
* @return
* @throws IOException
* @throws JSONException
*/
private JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
Upvotes: 0
Views: 210
Reputation: 51711
Wrap the response text into JSONArray
instead.
List<String> countries = new ArrayList<String>();
String json = "[\"england\",\"france\",\"germany\",\"america\"," +
"\"denmark\",\"italey\",\"greece\",\"portugal\",\"poland\"]";
JSONArray countryArr = new JSONArray(json);
for (int i = 0; i < countryArr.length(); i++) {
countries.add(countryArr.getString(i));
}
System.out.println(countries);
Output :
[england, france, germany, america, denmark, italey, greece, portugal, poland]
Upvotes: 1