【发布时间】:2014-11-05 05:58:53
【问题描述】:
我正在尝试使用此代码从 URL 解析 Json 数组。
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);
}
}
它适用于非 URL 输入并解析得很好,但使用 fromURL 输入时它会显示“预期 BEGIN_ARRAY 但为 STRING”。
我认为 fromURL 它在 [ 前面有 \" ,这就是它有问题的原因,但我不知道如何解决它。
【问题讨论】:
-
如果我请求该 URL,我会在文件内容中得到一个
<meta charset="UTF-8">。你可能想跳过那个。