0

我有一个网址。其中有一个这种格式的简单 JSON 数组:

["england","france","germany","america","denmark","italy","greece","portugal","poland"]

我需要做的就是从 Java 中读取它,并将其放入ArrayList.

这听起来很简单,但我已经做了好几个小时了。

这是我到目前为止所做的:

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();
        }
    }
}
4

1 回答 1

1

将响应文本包装成JSONArray代替。

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);

输出

[england, france, germany, america, denmark, italey, greece, portugal, poland]
于 2013-10-26T21:53:24.377 回答