在URL中从JSON创建Java数组

时间:2013-10-26 21:40:04

标签: java android json arraylist

我有一个网址。其中有一个简单的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();
        }
    }
}

1 个答案:

答案 0 :(得分: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]