我正在尝试使用此代码从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);
}
}
它与nonURL输入一起使用并且解析得很好,但是使用fromURL输入它会显示“预期BEGIN_ARRAY但是STRING”。
我在想,它来自于它之前的[这就是它存在问题的原因,但我对如何解决这个问题缺乏想法。
答案 0 :(得分:0)
您从网址获得的回复第一行有<meta charset="UTF-8">
(您可以通过浏览器直接浏览网址并查看其来源来查看):
要使其成为有效的json,您可以删除该行:
String fromURL = readUrl("http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php");
fromURL = fromURL.replace("<meta charset=\"UTF-8\">", "");
Item[] data = gson.fromJson(fromURL, Item[].class);
修改强> http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php的当前回复:
<meta charset="UTF-8">
[{"id":"1","name":"Mine raamatukokku","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"Mine õpi!"},{"id":"2","name":"Mine jooksma","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"Sport on hea"},{"id":"3","name":"Tee uinak","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"1 tund"}]