簡體   English   中英

如何將逗號分隔和雙引號的單詞字符串轉換為 Java 中的字符串列表/數組

[英]How to convert comma separated and double quoted words string to list/array of strings in Java

我有以下輸入字符串:

"["role_A","role_B","role_C"]"

我想將其轉換為包含所有值(role_A、role_B、role_C)的字符串列表/數組。

我已經使用以下代碼完成了:

  String allRoles = roles.replace("\"","").replaceAll("\\[", "").replaceAll("\\]","").split(",");

任何人都可以建議使用Java8更清潔或更好的方法!

如果字符串本身中有引號,則現有示例和替換引號的示例可能會中斷。 您可以使用 JSONArray 對其進行解析,然后在需要時轉換為列表

String x = "[\"role_A\",\"role_B\",\"role_C\"]";
JSONArray arr = new JSONArray(x);
List<String> list = new ArrayList<String>();
for (Object one : arr) {
    list.add((String)one);
}
System.out.println(list); //prints [role_A, role_B, role_C]
System.out.println(list.size()); //prints 3

json.jar可以在Maven 存儲庫中找到

String s = "[\"role_A\",\"role_B\",\"role_C\"]";
String[] res = s.split("\\[")[1].split(",");
for (String str : res) {
    str = str.replace("]", "").replace("\"", "");
}

結果數組res是您想要的數組。

這應該可以解決問題:

String[] arr = s.substring(2, s.length()-2).split("\",\"");

最簡單的解決方案是使用 GSON 或 Jackson 或任何 Json 轉換器。 但如果您想手動執行此操作,您可以使用正則表達式刪除任何符號並用逗號分隔。 但我建議改用圖書館,讓你的生活更輕松。

ObjectMapper mapper = new ObjectMapper();
            List<String> list = mapper.readValue("[\"role_A\",\"role_B\"]",
                    mapper.getTypeFactory().constructCollectionType(List.class,
                    String.class));

實現這一目標的一種方法是:

List<String> roles = Stream.of(rolesStr.replaceAll("[\"\\[\\]]","").split(",")).collect(Collectors.toList());

System.out.println(roles);

output:

[role_A, role_B, role_C]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM