我想使用此代碼從URL解析Json數組。預計BEGIN_ARRAY,但是STRING
public class Main {
static class Item {
@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("timelimitstart")
public String timelimitstart;
@SerializedName("timelimitend")
public String timelimitend;
@SerializedName("esttime")
public String esttime;
@SerializedName("location")
public String location;
@SerializedName("description")
public String description;
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
String fromURL = readUrl("http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php");
String nonURL = "[{\"id\":\"1\",\"name\":\"Mine raamatukokku\",\"timelimitstart\":\"\",\"timelimitend\":\"\",\"esttime\":\"00:00:00\",\"location\":\"\",\"description\":\"Mine Ƶpi!\"},{\"id\":\"1\",\"name\":\"Mine raamatukokku\",\"timelimitstart\":\"\",\"timelimitend\":\"\",\"esttime\":\"00:00:00\",\"location\":\"\",\"description\":\"Mine Ƶpi!\"}]";
Item[] data = gson.fromJson(nonURL, Item[].class);
}
}
它的工作原理與nonURL輸入和分析得很好,但與fromURL輸入它說:「預期BEGIN_ARRAY但STRING」。
我認爲fromURL它\」中的[面前,這就是爲什麼它有問題,但我出的關於如何解決它的想法。你
如果我請求URL,得到了一個'<元的charset = 「UTF-8」>'在文件的內容。你可能想跳過這個。 – mabi 2014-11-04 18:04:57