2014-09-03 166 views
0

我有以下字符串如何從以下JSON字符串獲取字符串[]?

["[email protected]","[email protected]"] 

我使用String.split(",")得到的String []。但數組內容包括「[」和「「」的。

我需要出去引號,以獲得實際的字符串。是否有一個圖書館或方法與我能做到嗎?

目前我做的這樣的。

recipients = recipients.replace("\"", ""); 
    recipients = recipients.replace("[", ""); 
    recipients = recipients.replace("]", ""); 
    String[] totalRecipients = recipients.split(","); 
+1

爲什麼不嘗試解析JSON字符串而不是試圖對其進行字符串操作?你會得到一個'List '來解析那個可以很容易地轉換爲一個字符串數組的JSON字符串。 – SudoRahul 2014-09-03 08:59:40

回答

4

使用boonjackson第三方庫將json字符串反序列化爲java對象。

寶示例 -

ObjectMapper mapper = JsonFactory.create(); 
String[] recipientArray = mapper.readValue(recipients , String[].class, String.class); 

查找的Java寶VS傑克遜JSON - 基準 - here

enter image description here

來源:Link

+2

此條形圖並不真正有用。它試圖說什麼?那傑克遜的速度是Boon的25%嗎?或者,傑克遜需要25ms的時間才能讓Boon需要大約100ms的時間? – Tom 2014-09-03 09:21:11

+0

它是吞吐量圖縱軸表示吞吐量。從鏈接資源中獲得更好的理解。 – 2014-09-03 09:40:55

+0

@SubhrajyotiMajumder謝謝。我的項目已經在使用net.sf.json庫。我沒有找到我可以用同樣的方法。 – phoenix 2014-09-03 09:55:16

1

我建議你使用JSON庫來解決它。

http://jackson.codehaus.org/

String s = "[\"[email protected]\",\"[email protected]\"]"; 

ObjectMapper mapper = new ObjectMapper(); 
JsonNode node = mapper.readValue(s); 
for(JsonNode n : node){ 
....... 
} 
+1

新的主頁在這裏:http://wiki.fasterxml.com/JacksonHome :)。 – Tom 2014-09-03 09:02:54

+0

哈哈,謝謝,只是從谷歌搜索它。 – 2014-09-03 09:04:37

1

你可以使用google's gson和你的JSON解碼到String[]你可以簡單地使用這行代碼

Gson gson = new Gson(); 
String[] myArray = gson.fromJson(yourjson,String[].class);