2013-05-08 69 views
0

我有一個來自http請求的字符串,我想用其他人替換多個字符和字符串。我可以這樣做嗎?用數組更有效的方式?如何將java多個字符和字符串替換爲其他字符;

 String result =" "hourly": [ {"cloudcover": "0", "humidity": "93", "precipMM": "0.0", "pressure": "1013", "sigHeight_m": "0.7", "swellDir": "70", "swellHeight_m": "0.5", "swellPeriod_secs": "1.0", "tempC": "9", "tempF": "48", "time": "0", "v"; 
     String result2 = result.replace("{", " "); 
     String result3 = result2.replace("}", " "); 
     String result4 = result3.replace("[", " "); 
     String result5 = result4.replace("]", " "); 
     String result6 = result5.replace("\"", ""); 

     String result7 = result6.replaceAll("......", "   "); 
     String result8 = result7.replaceAll("cloudcover", "\n  \ncloudcover"); 
     String result9 = result8.replaceAll("winddir:", " \nwinddir:"); 
     String result10 = result9.replaceAll("tempC:", " \ntempC:"); 

    WeatherInfos.setText(result10);//Shows the weather info 
+0

我認爲在json resoponse所以沒有必要更換隻是使用json..and然後替換字符串,如果它requried – QuokMoon 2013-05-08 09:55:39

+0

我怎麼能做到這一點? – antkan 2013-05-08 09:57:06

+0

你可以使用'regex'! – SudoRahul 2013-05-08 09:57:10

回答

0
任何你想去的地方

嘗試以下

String result = "{\"hourly\": [ {\"cloudcover\": \"15\", \"humidity\": \"93\", \"pressure\": \"1013\", \"tempC\": \"9\", \"winddir\": \"25\"}]}"; 

if(!result.startsWith("{")) 
    result = "{" + result + "}"; 

JSONObject JSONResult = new JSONObject(result); 
JSONResult = (JSONObject) JSONResult.getJSONArray("hourly").get(0); 

String cloudcover = JSONResult.getString("cloudcover"); 
String tempC= JSONResult.getString("tempC"); 
String winddir= JSONResult.getString("winddir"); //i do not see winddir in your result 

Toast.makeText(getapplicationContext(), "Cloud Cover is "+ cloudcover , Toast.LENGTH_LONG).show(); 

現在打印cloudcover,winddir和tempC。

+0

好的。謝謝! – antkan 2013-05-08 10:27:00

+0

如何獲取winddir後的信息:25? – antkan 2013-05-08 10:29:52

+0

例如「tempC:19」我想將其轉換爲溫度爲19 C – antkan 2013-05-08 10:36:14

相關問題