private static JSONObject convert(String text) {
// state
final List<JSONObject> items = new LinkedList<>();
final Set<ChatColor> formatting = EnumSet.noneOf(ChatColor.class);
final StringBuilder current = new StringBuilder();
ChatColor color = null;
// work way through text, converting colors
for (int i = 0; i < text.length(); ++i) {
char ch = text.charAt(i);
if (ch != ChatColor.COLOR_CHAR) {
// no special handling
current.append(ch);
continue;
}
if (i == text.length() - 1) {
// ignore color character at end
continue;
}
// handle colors
append(items, current, color, formatting);
ChatColor code = ChatColor.getByChar(text.charAt(++i));
if (code == ChatColor.RESET) {
color = null;
formatting.clear();
} else if (code.isFormat()) {
formatting.add(code);
} else {
color = code;
formatting.clear();
}