2016-05-12 22 views
0

我收到了JSON對象,並對其進行解析。如何使用HashMap將多個值放入ArrayList?

數據如下。

[Parsed_showinfo_2 @ 0x9b4da80] n:88 pts:17425897 pts_time:726.079 pos:149422375 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:1 type:I checksum:48E13810 plane_checksum:[48E13810] 
[Parsed_showinfo_2 @ 0x9b4da80] n:89 pts:17471943 pts_time:727.998 pos:149646339 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:0 type:P checksum:1AAD40E0 plane_checksum:[1AAD40E0] 
[Parsed_showinfo_2 @ 0x9b4da80] n:90 pts:17503975 pts_time:729.332 pos:149806608 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:1 type:I checksum:3DA5F0DB plane_checksum:[3DA5F0DB] 

然後,我沒有使用JSONParser(),因爲我需要點,pts_time值分析數據。

FileInputStream fstream = new FileInputStream("myfile"); 
DataInputStream in = new DataInputStream(fstream); 
BufferedReader buff = new BufferedReader(new InputStreamReader(in)); 

//Which type put to ? 
HashMap<String, ?> map = new HashMap<String, ?>(); 
//Should I use ArrayList too? 
//ArrayList<HashMap<String, ?>> list = new ArrayList<HashMap<String, ?>>(); 

try { 
    while (strLine = buff.readLine()) != null) { 
     s = strLine.split(" "); 
     pts = Long.parseLong(s[4].split(":")[1]); 
     ptstime = s[5].split(":")[1]; 
    } 
} catch (IOException ex) { } 

我想在while循環中創建多個數組,並返回結果值。

像這樣:

["pts": {1, 2, 3, 4, 5}, "ptstime": {10.11, 13.003, 15.12, 16.53, 18.10}] 

ptsptstime是關鍵。

我怎樣才能在while循環

+0

哪裏JSON對象?你在哪裏調用JSON解析器?你從檔案中讀到什麼?以及爲什麼通過'DataInputStream'? – Thilo

+0

您可以在循環後將值添加到哈希映射中, –

回答

1

這裏的編碼是你如何能做到這一點:

Map<String, List<Object>> map = new HashMap<>(); 
... 
while (strLine = buff.readLine()) != null) { 
    s = strLine.split(" "); 
    pts = Long.parseLong(s[4].split(":")[1]); 
    List<String> listPts = map.get("pts"); 
    if (listPts == null) { 
     listPts = new ArrayList<>(); 
     map.put("pts", listPts); 
    } 
    listPts.add(pts); 
    // Here apply the same logic to the rest 
} 

但更好的方法可以是使用MapList代替,就像這樣:

List<Map<String, Object>> list = new ArrayList<>(); 
while (strLine = buff.readLine()) != null) { 
    s = strLine.split(" "); 
    Map<String, String> map = new HashMap<>(); 
    list.add(map); 
    pts = Long.parseLong(s[4].split(":")[1]); 
    map.put("pts", pts); 
    // Here apply the same logic to the rest 
} 
+0

非常感謝。我用你的代碼來使用HashMap。 :) – ofleaf

+0

@ofleaf好消息 –

1

什麼是DataInputStream爲你使用它只是作爲參數爲InputStreamReader,該FileInputStream應該已經好了。

至於你的問題,我想你想要的是

Map<String, List<?>> map = new HashMap<>(2); 
map.put("pts", new ArrayList<Long>()); 
map.put("ptstime", new ArrayList<Long>()); 

然後在while循環類似

map.get("pts").add(pts.toString()); 
map.get("ptstime").add(ptstime);