JSON is one of the most common text formats for Web APIs, configuration, messaging, and language-independent data exchange. Its grammar is small, but strict JSON is not identical to a JavaScript object, a Java Map, or the relaxed input accepted by some JSON libraries.
1. What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based, language-independent data interchange syntax.
JSON borrowed braces, brackets, colons, and commas from JavaScript object literals, but it is not executable JavaScript and does not require a language to use JavaScript’s internal data types. An object may become a Java object or Map, a Python dict, or an equivalent record structure. An array may become a Java List or another language’s sequence.
2. Who created JSON, and how did it become a standard?
JavaScript-like object notation was not invented from nothing by one person. Douglas Crockford is generally credited with naming, documenting, and promoting JSON. He recalled recognizing the pattern’s value for network data exchange while working at State Software in April 2001, then used JSON.org to describe and distribute the syntax.
JSON spread quickly for several reasons:
- Browsers could process the structure easily, and it was more compact than the XML commonly used at the time.
- Objects and arrays map to universal structures available in nearly every programming language.
- JSON.org provided a short specification and links to implementations in many languages.
- Ajax and Web APIs created strong demand for lightweight data exchange.
- Standards organizations gradually stabilized its grammar and interoperability rules.
The main standardization milestones were:
- 2001: JSON was first presented publicly through JSON.org.
- 2006: the IETF published RFC 4627 and registered the
application/jsonmedia type. - 2009: ECMAScript 5 included normative JSON grammar plus
JSON.parseandJSON.stringify. - 2013: Ecma International published ECMA-404.
- 2017: the IETF published the current Internet Standard RFC 8259, and ECMA-404 Second Edition aligned with it.
3. JSON syntax
A JSON text represents one JSON value. Objects and arrays are most common, but the current standard also permits a top-level string, number, boolean, or null.
An object uses {}. Member names must be double-quoted strings, a colon separates each name from its value, and commas separate members:
{
"name": "Wangz Tools",
"enabled": true,
"items": [1, 2, 3],
"settings": {
"theme": "system"
}
}
An array uses [], preserves element order, and may contain mixed JSON types:
["text", 42, true, null, {"id": 1}, [1, 2]]
Neither object members nor array elements may end with a trailing comma. Property names cannot omit double quotes or use single quotes.
4. The six JSON value types
JSON has only six value types:
| Type | Example | Meaning |
|---|---|---|
| object | {"name":"A"} |
Collection of string names and values |
| array | [1,2,3] |
Ordered list of values |
| string | "hello" |
Double-quoted Unicode text |
| number | -12.5e2 |
Decimal number syntax |
| boolean | true, false |
The only two boolean literals |
| null | null |
Explicit absence of a value |
JSON has no native date, binary, enum, undefined, or class-instance type. Dates are commonly represented by ISO 8601 strings or Unix timestamps. Binary data is commonly encoded as Base64 text. The API contract must define the actual meaning.
The literals true, false, and null are lowercase and case-sensitive. True, FALSE, and NULL are invalid. Quoted values such as "true" are strings, not booleans.
5. Strings and escape sequences
JSON strings require double quotes. A backslash introduces these escapes:
| Escape | Meaning |
|---|---|
\" |
Quotation mark |
\\ |
Backslash |
\/ |
Solidus; escaping it is optional |
\b |
Backspace |
\f |
Form feed |
\n |
Line feed |
\r |
Carriage return |
\t |
Tab |
\uXXXX |
Four-digit hexadecimal Unicode escape |
Quotation marks, backslashes, and control characters U+0000 through U+001F must be escaped. Chinese text, Latin text, and most other Unicode characters can appear directly in UTF-8 JSON; they do not all need \uXXXX encoding.
{
"quote": "She said: \"Hello\"",
"path": "C:\\Users\\Admin",
"lines": "first line\nsecond line",
"symbol": "\u00A9"
}
Do not generate JSON by concatenating untrusted strings. Let Gson, Jackson, JSONObject, or another serializer escape the content correctly.
6. Number rules and precision
JSON numbers use decimal notation and may contain a minus sign, fraction, and exponent:
[0, -12, 3.14, 6.02e23, 1E-8]
These forms are invalid:
+1: a leading plus sign is not allowed.01: the integer component cannot contain unnecessary leading zeros..5or1.: digits are required on both sides of a decimal point.0xFF,0b10, or077: hexadecimal, binary, and octal forms are unsupported.NaN,Infinity, and-Infinity: these are not JSON numbers.
JSON specifies a textual number grammar, not whether a receiver stores a value as int, long, double, or arbitrary-precision decimal. Many environments use IEEE 754 binary64. Integers from -9007199254740991 through 9007199254740991 are the reliable exact interoperability range across common implementations.
Identifiers, snowflake IDs, bank-card numbers, and other values that must preserve every digit should be strings:
{
"orderId": "9223372036854775807",
"amount": "19.99"
}
An API contract should consistently define whether money is a string, integer minor units, or a decimal number.
7. How can JSON contain legal comments?
Standard JSON has no comment syntax. Neither form below is valid JSON:
// line comment
/* block comment */
JSONC, JSON5, and some editor configurations accept comments, but they are extensions. A standard JSON parser is not required to accept them.
If a business protocol permits extra fields, documentation can be represented as ordinary data:
{
"_comment": "timeout is measured in seconds",
"timeout": 30
}
Use a _comments array for multiple notes. A more interoperable approach is to keep comments in API documentation, JSON Schema, or a nearby README. Confirm that a receiver permits extra fields before sending comment properties.
8. Common JSON libraries for Java
Common Java choices include:
- Jackson: a frequent Spring Boot default with data binding, streaming, and tree APIs.
- Gson: Google’s library with a compact API for ordinary serialization and deserialization.
- JSON-B: the Jakarta JSON Binding standard API.
org.json/JSONObject: a lightweight tree API; Android includes related classes.
A project should choose one primary library instead of mixing several tree and object models throughout business code.
9. Common Gson usage
Convert between an object and JSON:
import com.google.gson.Gson;
record User(String name, boolean active) {}
Gson gson = new Gson();
String json = gson.toJson(new User("Wangz", true));
User user = gson.fromJson(json, User.class);
Preserve generic type information when reading collections:
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
Type type = new TypeToken<List<User>>() {}.getType();
List<User> users = gson.fromJson(jsonArray, type);
Use the tree API when a dedicated Java class is unnecessary:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
JsonObject root = JsonParser.parseString(json).getAsJsonObject();
String name = root.get("name").getAsString();
boolean active = root.get("active").getAsBoolean();
Do not interpolate untrusted text into a JSON string. Call toJson so Gson handles quotation marks, backslashes, and control characters.
10. Common JSONObject usage
Android provides org.json.JSONObject and JSONArray:
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject root = new JSONObject(json);
String name = root.getString("name");
boolean active = root.optBoolean("active", false);
String nickname = root.optString("nickname", "");
JSONArray items = root.optJSONArray("items");
getXxx throws when a field is absent or incompatible. optXxx can return a default and works well for optional fields, but defaults should not hide missing required data.
Build JSON with typed values:
JSONObject output = new JSONObject()
.put("name", "Wangz")
.put("active", true)
.put("items", new JSONArray().put(1).put(2))
.put("nickname", JSONObject.NULL);
String json = output.toString();
Use JSONObject.NULL when Android must emit a JSON null. Passing Java null to put may remove the property, so the two values are not interchangeable.
11. Formatting, minifying, and validation
- Formatting adds indentation and line breaks without changing data semantics.
- Minifying removes unnecessary whitespace.
- Validation parses the text according to JSON grammar and reports syntax errors.
A formatter cannot determine whether business data is correct. Valid JSON can still omit required fields, use the wrong currency unit, or violate an API model. Use JSON Schema, Java Bean Validation, or business rules for structural and semantic validation.