Java flat JSON object parser with clear errors
Java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class FlatJson {
private static final Pattern PAIR = Pattern.compile("\"([^\"]+)\"\\s*:\\s*(\"[^\"]*\"|[^,}\\s]+)");
public static Map<String, String> parse(String s) {
Map<String, String> out = new LinkedHashMap<>();
String body = s.trim();
if (!body.startsWith("{") || !body.endsWith("}"))
throw new IllegalArgumentException("invalid JSON: expected an object, got: " + s);
Matcher m = PAIR.matcher(body.substring(1, body.length() - 1));
while (m.find()) {
String v = m.group(2);
out.put(m.group(1), v.startsWith("\"") ? v.substring(1, v.length() - 1) : v);
}
if (out.isEmpty() && !body.matches("\\{\\s*}"))
throw new IllegalArgumentException("invalid JSON: no key:value pairs in " + s);
return out;
}
}