I have an array like this: ["one", two"]
If I make array.toString().replace("[", "").replace("]", "").trim();
, I will have: "one, two"
What I really want is "one", "two"
How can I do this?
EDIT:
This is a simple program to explain my question:
ArrayList<String> array = new ArrayList<>();
array.add("one");
array.add("two");
String stringArray = array.toString().replace("[", "").replace("]", "");
Gson gson = new Gson();
String json = gson.toJson(stringArray);
System.out.println(json);
You can try with
array.stream().map(s->"\""+s+"\"").collect(Collectors.joining(", "));
which will first surround each strings with quotes, then join them using ,
For Java 7
String delimiter = ", ";
StringBuilder sb = new StringBuilder();
if (!array.isEmpty()) {
sb.append('"').append(array.get(0)).append('"');
}
for (int i = 1; i < array.size(); i++) {
sb.append(delimiter).append('"').append(array.get(i)).append('"');
}
String result = sb.toString();
Well, just replace comma's with some extra "
's
array.toString().replace("[", "").replace("]", "").trim().replace(", ", "\", \"")
(Not tested, but you get the idea)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.