JSON Small and Fast Parser - A lightweight, high-performance JSON processing library for Java
—
This document covers the essential JSON operations using JSONValue, JSONObject, and JSONArray - the primary classes for JSON parsing, creation, serialization, and basic manipulation.
JSONValue provides static utility methods for all common JSON operations. It serves as the main entry point for parsing, serialization, and validation.
public static Object parse(String s);
public static Object parse(Reader in);
public static Object parse(InputStream in);
public static Object parse(byte[] in);Parse JSON from various input sources using permissive mode (fastest, handles malformed JSON gracefully).
// Parse JSON string to generic Object
Object result = JSONValue.parse("{\"name\": \"John\", \"age\": 30}");
// Parse from Reader
Reader reader = new StringReader("{\"active\": true}");
Object data = JSONValue.parse(reader);
// Parse from byte array
byte[] jsonBytes = "{\"count\": 42}".getBytes();
Object parsed = JSONValue.parse(jsonBytes);public static <T> T parse(String in, Class<T> mapTo);
public static <T> T parse(Reader in, Class<T> mapTo);
public static <T> T parse(InputStream in, Class<T> mapTo);
public static <T> T parse(byte[] in, Class<T> mapTo);Parse JSON directly to specific Java types.
// Parse to JSONObject
JSONObject obj = JSONValue.parse("{\"name\": \"Alice\"}", JSONObject.class);
// Parse to custom class
MyUser user = JSONValue.parse(jsonString, MyUser.class);
// Parse from InputStream to specific type
InputStream stream = new FileInputStream("data.json");
MyData data = JSONValue.parse(stream, MyData.class);public static <T> T parse(String in, T toUpdate);
public static <T> T parse(Reader in, T toUpdate);
public static <T> T parse(InputStream in, T toUpdate);Parse JSON and update fields in existing object instances.
MyUser existingUser = new MyUser();
existingUser.setId(123);
// Parse JSON and update existing object (preserves existing fields not in JSON)
JSONValue.parse("{\"name\": \"Updated Name\"}", existingUser);public static Object parseWithException(String input) throws ParseException;
public static Object parseWithException(Reader in) throws IOException, ParseException;
public static Object parseWithException(InputStream in) throws IOException, ParseException;
public static Object parseWithException(byte[] in) throws IOException, ParseException;
public static <T> T parseWithException(String in, Class<T> mapTo) throws ParseException;Parse with explicit exception throwing instead of returning null on error.
public static Object parseStrict(String s) throws ParseException;
public static Object parseStrict(Reader in) throws IOException, ParseException;Parse using strict RFC4627 compliance (rejects malformed JSON).
public static Object parseKeepingOrder(String in);
public static Object parseKeepingOrder(Reader in);Parse JSON while preserving the order of object fields.
public static String toJSONString(Object value);
public static String toJSONString(Object value, JSONStyle compression);
public static void writeJSONString(Object value, Appendable out) throws IOException;
public static void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException;Convert Java objects to JSON strings or write to streams.
Object data = Map.of("name", "John", "age", 30);
// Basic serialization
String json = JSONValue.toJSONString(data);
// Serialization with compression style
String compressed = JSONValue.toJSONString(data, JSONStyle.MAX_COMPRESS);
// Write to StringBuilder/Writer
StringBuilder sb = new StringBuilder();
JSONValue.writeJSONString(data, sb);
// Write to file
FileWriter writer = new FileWriter("output.json");
JSONValue.writeJSONString(data, writer, JSONStyle.NO_COMPRESS);
writer.close();public static boolean isValidJson(String s);
public static boolean isValidJson(Reader in) throws IOException;
public static boolean isValidJsonStrict(String s);
public static boolean isValidJsonStrict(Reader in) throws IOException;Validate JSON without parsing to objects.
// Permissive validation
boolean valid1 = JSONValue.isValidJson("{name: 'John'}"); // true (allows unquoted keys)
// Strict validation
boolean valid2 = JSONValue.isValidJsonStrict("{name: 'John'}"); // false (requires quoted keys)
boolean valid3 = JSONValue.isValidJsonStrict("{\"name\": \"John\"}"); // truepublic static String compress(String input);
public static String compress(String input, JSONStyle style);
public static String uncompress(String input);
public static String escape(String s);
public static String escape(String s, JSONStyle compression);
public static void escape(String s, Appendable ap);
public static void escape(String s, Appendable ap, JSONStyle compression);Utility methods for JSON string manipulation.
// Compress JSON (remove whitespace)
String compressed = JSONValue.compress("{ \"name\" : \"John\" }"); // {"name":"John"}
// Escape special characters
String escaped = JSONValue.escape("Text with \"quotes\" and \n newlines");
// Uncompress (add readable formatting)
String readable = JSONValue.uncompress("{\"name\":\"John\"}");public static <T> void remapField(Class<T> type, String jsonFieldName, String javaFieldName);
public static <T> void registerWriter(Class<?> cls, JsonWriterI<T> writer);
public static <T> void registerReader(Class<T> type, JsonReaderI<T> mapper);Configure field mapping and custom serialization/deserialization.
// Remap field names between JSON and Java
JSONValue.remapField(MyUser.class, "first_name", "firstName");
// Register custom serializer
JSONValue.registerWriter(LocalDate.class, new DateWriter());
// Register custom deserializer
JSONValue.registerReader(LocalDate.class, new DateReader());JSONObject extends HashMap<String, Object> and implements JSON-aware interfaces for object manipulation.
public JSONObject();
public JSONObject(int initialCapacity);
public JSONObject(Map<String, ?> map);public JSONObject appendField(String fieldName, Object fieldValue);Add fields using fluent API pattern.
JSONObject user = new JSONObject()
.appendField("name", "Alice")
.appendField("age", 25)
.appendField("active", true)
.appendField("roles", Arrays.asList("admin", "user"));public String getAsString(String key);
public Number getAsNumber(String key);Extract values with automatic type conversion.
JSONObject obj = new JSONObject()
.appendField("name", "John")
.appendField("age", 30)
.appendField("score", 95.5);
String name = obj.getAsString("name"); // "John"
Number age = obj.getAsNumber("age"); // 30
Number score = obj.getAsNumber("score"); // 95.5
// Safe conversion - returns null if key doesn't exist or cannot convert
String missing = obj.getAsString("missing"); // null
Number invalid = obj.getAsNumber("name"); // null (can't convert "John" to number)public void merge(Object o2);
public void merge(Object o2, boolean overwrite);Merge with other objects or JSONObjects.
JSONObject base = new JSONObject()
.appendField("name", "Alice")
.appendField("age", 25);
JSONObject update = new JSONObject()
.appendField("age", 26)
.appendField("city", "New York");
// Merge with overwrite (default)
base.merge(update);
// Result: {"name": "Alice", "age": 26, "city": "New York"}
// Merge without overwriting existing fields
JSONObject base2 = new JSONObject()
.appendField("name", "Bob")
.appendField("age", 30);
base2.merge(update, false);
// Result: {"name": "Bob", "age": 30, "city": "New York"} (age not overwritten)public String toJSONString();
public String toJSONString(JSONStyle compression);
public String toString(JSONStyle compression);
public void writeJSONString(Appendable out) throws IOException;
public void writeJSONString(Appendable out, JSONStyle compression) throws IOException;Convert to JSON strings or write to streams.
JSONObject obj = new JSONObject()
.appendField("name", "Test")
.appendField("value", 42);
// Basic serialization
String json = obj.toJSONString(); // {"name":"Test","value":42}
// With formatting
String formatted = obj.toJSONString(JSONStyle.NO_COMPRESS);
// Write to stream
StringBuilder sb = new StringBuilder();
obj.writeJSONString(sb, JSONStyle.MAX_COMPRESS);public static String escape(String s);
public static String toJSONString(Map<String, ? extends Object> map);
public static String toJSONString(Map<String, ? extends Object> map, JSONStyle compression);
public static void writeJSON(Map<String, ? extends Object> map, Appendable out) throws IOException;
public static void writeJSON(Map<String, ? extends Object> map, Appendable out, JSONStyle compression) throws IOException;
public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException;Static methods for working with Maps and individual key-value pairs.
JSONArray extends ArrayList<Object> and implements JSON-aware interfaces for array manipulation.
public JSONArray();
public JSONArray(int initialCapacity);public JSONArray appendElement(Object element);Add elements using fluent API pattern.
JSONArray numbers = new JSONArray()
.appendElement(1)
.appendElement(2)
.appendElement(3);
JSONArray mixed = new JSONArray()
.appendElement("string")
.appendElement(42)
.appendElement(true)
.appendElement(new JSONObject().appendField("nested", "object"));public void merge(Object o2);Merge with other arrays or objects.
JSONArray arr1 = new JSONArray()
.appendElement("a")
.appendElement("b");
JSONArray arr2 = new JSONArray()
.appendElement("c")
.appendElement("d");
// Merge arrays (concatenation)
arr1.merge(arr2);
// Result: ["a", "b", "c", "d"]
// Merge with object (adds object as element)
JSONObject obj = new JSONObject().appendField("key", "value");
arr1.merge(obj);
// Result: ["a", "b", "c", "d", {"key": "value"}]public String toJSONString();
public String toJSONString(JSONStyle compression);
public String toString(JSONStyle compression);
public void writeJSONString(Appendable out) throws IOException;
public void writeJSONString(Appendable out, JSONStyle compression) throws IOException;Convert to JSON strings or write to streams.
JSONArray arr = new JSONArray()
.appendElement("item1")
.appendElement(42)
.appendElement(true);
// Basic serialization
String json = arr.toJSONString(); // ["item1",42,true]
// With formatting
String formatted = arr.toJSONString(JSONStyle.NO_COMPRESS);
// Write to stream
FileWriter writer = new FileWriter("array.json");
arr.writeJSONString(writer, JSONStyle.LT_COMPRESS);
writer.close();public static String toJSONString(List<? extends Object> list);
public static String toJSONString(List<? extends Object> list, JSONStyle compression);
public static void writeJSONString(List<? extends Object> list, Appendable out) throws IOException;
public static void writeJSONString(Iterable<? extends Object> list, Appendable out, JSONStyle compression) throws IOException;Static methods for serializing any List or Iterable to JSON.
List<String> stringList = Arrays.asList("apple", "banana", "cherry");
String json = JSONArray.toJSONString(stringList); // ["apple","banana","cherry"]
// Write any Iterable to stream
Set<Integer> numberSet = Set.of(1, 2, 3);
StringBuilder sb = new StringBuilder();
JSONArray.writeJSONString(numberSet, sb, JSONStyle.MAX_COMPRESS);// Create
JSONObject user = new JSONObject()
.appendField("id", 1)
.appendField("name", "John Doe")
.appendField("email", "john@example.com")
.appendField("active", true);
// Read - parse from JSON string
String jsonString = "{\"id\":1,\"name\":\"John Doe\",\"email\":\"john@example.com\",\"active\":true}";
JSONObject parsed = JSONValue.parse(jsonString, JSONObject.class);
// Update - modify existing object
parsed.put("name", "John Smith");
parsed.appendField("lastLogin", "2023-10-15");
// Delete - remove field
parsed.remove("email");
// Serialize back to JSON
String updated = JSONValue.toJSONString(parsed);// Create nested structure
JSONObject address = new JSONObject()
.appendField("street", "123 Main St")
.appendField("city", "Springfield")
.appendField("zipCode", "12345");
JSONArray phoneNumbers = new JSONArray()
.appendElement("555-1234")
.appendElement("555-5678");
JSONObject person = new JSONObject()
.appendField("name", "Alice Johnson")
.appendField("address", address)
.appendField("phoneNumbers", phoneNumbers);
// Access nested data
JSONObject parsedPerson = JSONValue.parse(person.toJSONString(), JSONObject.class);
JSONObject personAddress = (JSONObject) parsedPerson.get("address");
String city = personAddress.getAsString("city"); // "Springfield"
JSONArray phones = (JSONArray) parsedPerson.get("phoneNumbers");
String firstPhone = (String) phones.get(0); // "555-1234"// Process multiple JSON objects
String[] jsonStrings = {
"{\"name\": \"Alice\", \"score\": 95}",
"{\"name\": \"Bob\", \"score\": 87}",
"{\"name\": \"Charlie\", \"score\": 92}"
};
JSONArray results = new JSONArray();
for (String json : jsonStrings) {
JSONObject person = JSONValue.parse(json, JSONObject.class);
Number score = person.getAsNumber("score");
if (score != null && score.intValue() > 90) {
results.appendElement(person);
}
}
// Serialize high scorers
String highScorers = JSONValue.toJSONString(results);Install with Tessl CLI
npx tessl i tessl/maven-net-minidev--json-smart