将字符串(JSON)解析为POJO列表

时间:2014-09-25 18:40:17

标签: java json gson

我有以下代码可以从网络服务中读取。

   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);
   }

我有一个像

这样的RecordBean
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;
    }
}

输出字符串类似于

[{"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库。但没有成功。

1 个答案:

答案 0 :(得分:1)

你的Pojo需要默认的空构造函数,并且为了读取列表,你可以这样做:

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