0
URL이 있습니다. 내가 할 필요가 자바에서이 읽기 및 ArrayList
에 넣어됩니다URL에 JSON의 Java 배열을 만듭니다.
["england","france","germany","america","denmark","italy","greece","portugal","poland"]
: 그것에서는 이러한 형식의 간단한 JSON 배열이있다.
너무 간단하게 들렸지 만 몇 시간 동안 사용해 보았습니다.
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();
}
}
}