2
我使用Java創建比較數據A和每個數據。如何將Json字符串轉換爲List <HashMap <String,String >>?
首先,我從txt文件(文件中的數組類型)提取了數組數據。
其次,我的數據庫中有一個Json字符串數據(MySQL列類型:JSON)。
我分析txt文件,並列出
FileInputStream fstream = new FileInputStream(Path);
List<HashMap<String, String>> list = list(fstream);
public List<HashMap<String, String>> list(FileInputStream fstream) {
BufferedReader buff = new BufferedReader(new InputStreamReader(fstream));
List<HashMap<String, String> list = new ArrayList<>();
try {
while ((strLine = buff.readLine()) != null) {
s = strLine.split(" ");
HashMap<String, String> map = new HashMap<>();
pts = s[4].split(":")[1];
ptstime = s[5].split(":")[1];
map.put("pts", pts);
map.put("ptstime", getDurationString(ptstime));
if (pts_itv.equals("0") && ptstime_itv.equals("00:00")) {
map.put("pts_itv", "0");
map.put("ptstime_itv", "00:00");
}
else {
map.put("pts_itv", String.valueOf(Long.parseLong(pts) - Long.parseLong(pts_itv)));
map.put("ptstime_itv", getDurationString(String.valueOf(String.format("%.4f", Double.parseDouble(ptstime) - Double.parseDouble(ptstime_itv)))));
}
pts_itv = pts;
ptstime_itv = ptstime;
list.add(map);
}
}
catch (IOException ex) {
LOG.error("ERROR : " + ex.getLocalizedMessage() + ", " + ex.getMessage());
}
finally {
try {
buff.close();
} catch (IOException ex) {}
}
return list;
}
提取數據
[{pts_itv=0, ptstime=00:00:00.112792, pts=2707, ptstime_itv=00:00}, {pts_itv=192192, ptstime=00:00:08.12079, pts=194899, ptstime_itv=00:00:08.80}, {pts_itv=128128, ptstime=00:00:13.4595, pts=323027, ptstime_itv=00:00:05.3387}, {pts_itv=277277, ptstime=00:00:25.127, pts=600304, ptstime_itv=00:00:11.5532}]
我能得到索引鍵對象鍵。
list.get(0).get("pts_itv");
和第二數據(SELECT查詢從MySQL(JSON列型))
rs = Web.getInstance().getList(idx); //get data by sql query
jObj = (JSONObject) new JSONParser().parse(rs);
jArr = (JSONArray) jObj.get("data");
for (int i = 0; i < jArr.size(); i++) {
JSONObject Jarr = (JSONObject) jArr.get(i);
System.out.println(Jarr.get("PtsData"));
}
PtsData是
[{"pts": "81831", "pts_itv": "0", "ptstime": "00:00:03.40963", "ptstime_itv": "00:00"}, {"pts": "127877", "pts_itv": "46046", "ptstime": "00:00:05.32821", "ptstime_itv": "00:00:01.9186"}, {"pts": "157907", "pts_itv": "30030", "ptstime": "00:00:06.57946", "ptstime_itv": "00:00:01.2512"}]
java.lang.String
我想PtsData轉換爲第一數據類型。我如何將PtsData轉換爲List類型?
使用[jackson](https://github.com/FasterXML/jackson)或[Gson](https://github.com/google/gson) – Sampada
謝謝Sampada。我解決了使用gson.fromJson :) – ofleaf