2014-11-04 100 views
0

我想使用此代码从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它\”中的[面前,这就是为什么它有问题,但我出的关于如何解决它的想法。你

+0

如果我请求URL,得到了一个'<元的charset = “UTF-8”>'在文件的内容。你可能想跳过这个。 – mabi 2014-11-04 18:04:57

回答

0

响应从URL中有<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"}] 
+0

谢谢,这解决了我的问题。 – Jackstick 2014-11-05 09:05:22

相关问题