2014-08-30 122 views
0

我從服務中獲取此字符串。我想要一張地圖或json。它應該看起來像這樣。將字符串轉換爲HashMap

Map output 
    Total time taken:226006 
    nodea:10615 
    nodez:5308' 


String timingTrace = "Total time taken:226006.," 
      + "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\""; 

我試過的是以下代碼。我可以做更好的事嗎?任何可輕鬆將上述字符串轉換爲圖的庫。

if (timingTrace != null) { 
     arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,"); 
    } 
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":") 

Map<String,Object> timestamps = new HashMap<String, Object>(); 
timestamp.put(totaltime[0], totaltime[1]); 

String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:"); 

getMapped(nodetimestamp[1]); 

public void getMapped(String json) throws JSONException, ParseException { 
    JSONObject obj = new JSONObject(json); 
    Iterator<String> keys = obj.keys(); 
    while (keys.hasNext()) { 
     String key = keys.next(); 
     String timetaken = JsonPath.read(json, "$." + key + ".timeTaken"); 
     timestamp.put(key, timetaken); 
    } 
} 
+0

你的代碼有一些編譯錯誤。請參閱下面的答案。 – 2014-08-30 11:17:19

回答

0

您正在使用timestamp地圖<>在功能getMapped(String json),讓你的錯誤,因爲你沒有通過它,你在函數聲明的對象。

爲了得到輸出你提到的變化寫下面的代碼而不是函數getMapped(String json)

JSONObject obj = new JSONObject(nodetimestamp[1]); 
Iterator<String> keys = obj.keys(); 
while (keys.hasNext()) 
{ 
    String key = keys.next(); 
    String timetakenStr = obj.getString(key); 
    JSONObject child = new JSONObject(timetakenStr); 
    timestamps.put(key, child.getString("timeTaken")); 
} 

使用上面的代碼你Map<>將包含相同的你提什麼。 OutPut:

{nodea=10615, Total time taken=226006, nodez=5308}