2014-09-25 2 views
-2

웹 서비스에서 읽을 코드는 다음과 같습니다. 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

답변

1

귀하의 뽀조는 기본 빈 생성자를 필요로하고 목록을 읽기 위해, 당신은이 작업을 수행 할 수 있습니다

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

+1이이 질문의 대답이기 때문에 – Devrim