Skip to content
StringToJSON

Java — String to JSON

Convert a string to JSON in Java.

Jackson, Gson, or org.json — three libraries, three idioms, one job. Verify your payload with the free online converter above, then pick the pattern that matches your stack.

Escaped string

0 B

JSON

0 B

Output appears here.

Ready. Paste something above.

Everything runs locally in your browser — your data never leaves this page. Press⌘/Ctrl +Enter to run.

Java has no built-in JSON parser

Unlike Python or JavaScript, the Java standard library ships nothing that converts a string to JSON. Every approach means adding a dependency, so the first decision is which one.

Jackson — the default choice

ObjectMapper mapper = new ObjectMapper();

// straight onto your own type
User user = mapper.readValue(json, User.class);

// or a generic tree when the shape is unknown
JsonNode node = mapper.readTree(json);
int id = node.get("id").asInt();

// to a Map, no wrapper class needed
Map<String, Object> map =
    mapper.readValue(json, new TypeReference<Map<String, Object>>() {});

// object back to a JSON string
String out = mapper.writeValueAsString(user);

Jackson is what Spring Boot autoconfigures, so in most projects it is already on the classpath.readValue maps onto a class, readTree gives you an untyped tree, and theTypeReference trick works around type erasure when the target is a generic collection.

Gson — smaller and simpler

Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
String out = gson.toJson(user);

org.json — quick, but dated

JSONObject obj = new JSONObject(json);
String name = obj.getString("name");
JSONArray items = obj.getJSONArray("items");
String out = obj.toString(2);   // pretty-printed

The error everyone hits

org.json.JSONException: Value ... of type java.lang.String cannot be converted to JSONObject means the constructor received text that is not a JSON object. Three causes cover almost every case: the response was an HTML error page rather than JSON; the payload is a JSON array, so it needs new JSONArray(...); or the value is double-encoded — a quoted string that itself contains JSON.

// double-encoded: parse twice
String inner = new JSONObject("{\"body\":\"...\"}").getString("body");
JSONObject real = new JSONObject(inner);

Paste the raw value into the converter above — it unwraps the nested layers and shows you the actual structure, which is usually faster than adding print statements.

A note on records

Since Java 16, records pair well with Jackson: declarerecord User(int id, String name) and readValue populates it directly, no getters or setters required. Add@JsonIgnoreProperties(ignoreUnknown = true) so an extra field in the response does not break deserialization — APIs add fields, and failing on unknown properties is rarely the behaviour you want in a client.

Reuse your ObjectMapper

Constructing a new ObjectMapper for every request is the most common performance mistake in Java JSON code. The class is expensive to build because it caches reflection metadata for every type it has seen, and that cache is exactly what makes the second parse of a type fast. It is thread-safe once configured, so create one instance, configure it, and share it — as a static field, or as a Spring bean you inject. If you need different settings for one call site, derive a ObjectReader or ObjectWriter from the shared mapper rather than building a second one.

Nulls, Optionals and dates

Jackson maps a missing field and an explicit null to the same thing — a null field — which loses a distinction that sometimes matters in PATCH-style APIs. Registering theJdk8Module lets you use Optional to tell them apart. Java 8 dates need the JavaTimeModule, without which LocalDateTime serializes as a verbose object of its component parts rather than an ISO string; adddisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) alongside it. Spring Boot registers both modules for you, which is why the same code often behaves differently inside and outside the framework — a discrepancy worth knowing about before you spend an afternoon on it.

Naming, briefly

Java convert string to JSON, java string to json,convert string to JSON object in Java, java object string to JSON,java to string to JSON, convert string to JSON java, andstring to JSON java all describe the same call — the library you picked decides its name. Going the other way, convert Java object to JSON string iswriteValueAsString in Jackson, toJson in Gson, andtoString() on a JSONObject. Theonline string to JSON converter is useful for verifying a raw payload before you wire it into your Java application.

Frequently asked questions

How to convert a string to JSON in Java?
Java has no built-in parser, so pick a library. Jackson: new ObjectMapper().readValue(text, MyClass.class) or readTree(text) for a JsonNode. Gson: new Gson().fromJson(text, MyClass.class). org.json: new JSONObject(text). Paste the payload into the converter above to confirm it is valid JSON first.
How to convert a string to a JSON object in Java?
With org.json, new JSONObject(text) parses a string directly. With Jackson, new ObjectMapper().readTree(text) gives a JsonNode, or readValue(text, MyClass.class) maps it onto your own type. With Gson it is gson.fromJson(text, MyClass.class).
How to parse a string to a JSON object in Java?
Same call as converting a string to JSON — "parse" is just the name most Java APIs use. Jackson readValue / readTree, Gson fromJson, org.json new JSONObject(text). If the text is double-encoded (a quoted string that itself contains JSON), parse twice.
How to parse JSON to a string in Java?
Serialize with Jackson new ObjectMapper().writeValueAsString(obj), Gson new Gson().toJson(obj), or jsonObject.toString() in org.json. Jackson's writerWithDefaultPrettyPrinter() adds indentation.
How to read a JSON file as a string in Java?
Read the file into a String first — Files.readString(Path.of("data.json")) on Java 11+, or a BufferedReader on older versions — then parse that string with Jackson, Gson or org.json. Jackson can also skip the string: mapper.readValue(new File("data.json"), MyClass.class).
How to remove escape characters from a JSON string in Java?
Parse it. new JSONObject(text), Jackson readTree, or Gson fromJson each unescape \", \n and \t as part of parsing. If the value is double-encoded, parse once to get the inner string and again to get the object. The converter above unwraps nested layers automatically.
Why do I get "java.lang.String cannot be converted to JSONObject"?
The text you passed is not a JSON object — it is a bare string, a double-encoded payload, or an HTML error page. Print the raw value first. If it is a quoted literal containing JSON, parse it once to get the inner string and again to get the object.