2014-09-25 24 views
-2

我有以下代码可以从web服务读取。将字符串(JSON)解析为POJO列表

URL url = new URL("http://localhost:8080/search"); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Accept", "application/json"); 
    if (conn.getResponseCode() != 200) { 
     throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); 
    } 

    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); 
    String output=""; 
    System.out.println("Output from Server .... \n"); 
    while ((output = br.readLine()) != null) { 
     System.out.println(output); 
    } 

我有一个像

public class RecordBean implements Serializable{ 
    private long peerId; 
    private String filePath; 
    private String fileName; 
    private String ipAddress; 
    private String port; 

    public RecordBean(long peerId, String filePath, String fileName, String ipAddress, String port) { 
     this.peerId = peerId; 
     this.filePath = filePath; 
     this.fileName = fileName; 
     this.ipAddress = ipAddress; 
     this.port = port; 
    } 

    public long getPeerId() { 
     return peerId; 
    } 

    public void setPeerId(long peerId) { 
     this.peerId = peerId; 
    } 

    public String getFilePath() { 
     return filePath; 
    } 

    public void setFilePath(String filePath) { 
     this.filePath = filePath; 
    } 

    public String getFileName() { 
     return fileName; 
    } 

    public void setFileName(String fileName) { 
     this.fileName = fileName; 
    } 

    public String getIpAddress() { 
     return ipAddress; 
    } 

    public void setIpAddress(String ipAddress) { 
     this.ipAddress = ipAddress; 
    } 

    public String getPort() { 
     return port; 
    } 

    public void setPort(String port) { 
     this.port = port; 
    } 
} 

输出字符串RecordBean是像

[{"peerId":1234,"filePath":"/tmp/test","fileName":"testFile","ipAddress":"1.1.1.1","port":"1111"},{"peerId":1235,"filePath":"/tmp/test","fileName":"testFile","ipAddress":"2.2.2.2","port":"2222"},{"peerId":1236,"filePath":"/tmp/test","fileName":"testFile","ipAddress":"3.3.3.3","port":"3333"}] 

我将如何解析成RecordBeans的名单呢?我尝试过使用GSON库。但没有成功。

+2

这将帮助我们,如果你发布你尝试过什么。 – manouti 2014-09-25 18:41:30

回答

1

你的POJO的需要默认的空构造和阅读列表,你可以这样做:

Type listType = new TypeToken<List<RecordBean>>(){}.getType(); 
List<RecordBean> list2 = gson.fromJson(jsonString, listType); 
+0

+1,因为这是这个问题的答案。 – Devrim 2014-09-28 17:00:51