2014-11-04 163 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

相關問題