add basic support for json array values

This commit is contained in:
Marcel Haßlinger 2021-07-20 10:42:27 +02:00
parent 433cf1183f
commit dff48382c2
3 changed files with 64 additions and 3 deletions

View File

@ -4,6 +4,7 @@
## [Unreleased]
### Added
- Basic support for json array values
- Settings option to opt-out code assistance inside editor
- Kotlin support for key completion and annotation

View File

@ -0,0 +1,51 @@
package de.marhali.easyi18n.util;
import com.google.gson.JsonArray;
import org.apache.commons.lang.StringEscapeUtils;
import java.util.regex.Pattern;
/**
* Utility methods to read and write json arrays.
* @author marhali
*/
public class JsonArrayUtil {
public static String ARRAY_PREFIX = "!arr[";
public static String ARRAY_SUFFIX = "]";
public static char ARRAY_DELIMITER = ';';
public static String read(JsonArray array) {
StringBuilder builder = new StringBuilder(ARRAY_PREFIX);
for(int i = 0; i < array.size(); i++) {
if(i > 0) {
builder.append(ARRAY_DELIMITER);
}
String value = array.get(i).getAsString().replace(";", "\\;");
builder.append(StringUtil.escapeControls(value, true));
}
builder.append(ARRAY_SUFFIX);
return builder.toString();
}
public static JsonArray write(String concat) {
concat = concat.substring(ARRAY_PREFIX.length(), concat.length() - ARRAY_SUFFIX.length());
String regex = "(?<!\\\\)" + Pattern.quote(String.valueOf(ARRAY_DELIMITER));
JsonArray array = new JsonArray();
for(String element : concat.split(regex)) {
element = element.replace("\\" + ARRAY_DELIMITER, String.valueOf(ARRAY_DELIMITER));
array.add(StringEscapeUtils.unescapeJava(element));
}
return array;
}
public static boolean isArray(String concat) {
return concat != null && concat.startsWith(ARRAY_PREFIX) && concat.endsWith(ARRAY_SUFFIX);
}
}

View File

@ -27,8 +27,13 @@ public class JsonUtil {
public static void writeTree(String locale, JsonObject parent, LocalizedNode node) {
if(node.isLeaf() && !node.getKey().equals(LocalizedNode.ROOT_KEY)) {
if(node.getValue().get(locale) != null) {
String value = StringEscapeUtils.unescapeJava(node.getValue().get(locale));
parent.add(node.getKey(), new JsonPrimitive(value));
if(JsonArrayUtil.isArray(node.getValue().get(locale))) {
parent.add(node.getKey(), JsonArrayUtil.write(node.getValue().get(locale)));
} else {
String value = StringEscapeUtils.unescapeJava(node.getValue().get(locale));
parent.add(node.getKey(), new JsonPrimitive(value));
}
}
} else {
@ -78,7 +83,11 @@ public class JsonUtil {
}
Map<String, String> messages = leafNode.getValue();
String value = StringUtil.escapeControls(entry.getValue().getAsString(), true);
String value = entry.getValue().isJsonArray()
? JsonArrayUtil.read(entry.getValue().getAsJsonArray())
: StringUtil.escapeControls(entry.getValue().getAsString(), true);
messages.put(locale, value);
leafNode.setValue(messages);
}