The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Answer from user1931858 on Stack Overflow
Top answer
1 of 16
962

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

2 of 16
714

For the sake of the example lets assume you have a class Person with just a name.

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

Jackson (Maven)

My personal favourite and probably the most widely used.

ObjectMapper mapper = new ObjectMapper();

// De-serialize to an object
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John

// Read a single attribute
JsonNode nameNode = mapper.readTree("{\"name\": \"John\"}");
System.out.println(nameNode.get("name").asText());

Google GSON (Maven)

Gson g = new Gson();

// De-serialize to an object
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

// Read a single attribute
JsonObject jsonObject = new JsonParser().parseString("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John

Org.JSON (Maven)

This suggestion is listed here simply because it appears to be quite popular due to stackoverflow reference to it. I would not recommend using it as it is more a proof-of-concept project than an actual library.

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John
🌐
Medium
medium.com › swlh › getting-json-data-from-a-restful-api-using-java-b327aafb3751
Getting JSON Data From a RESTful API Using JAVA | by Gayanga Kuruppu | The Startup | Medium
August 4, 2020 - If the response code is not 200 (Successful) we throw a new exception, otherwise we use a scanner to go through the URL stream and write all the data we get into a string. Then using the JSON Simple library we parse that string into a JSON object. Then we can get the object (or array) we want from that object using its key.
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
Returns the object value to which the specified name is mapped. This is a convenience method for (JsonObject)get(name) to get the value.
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonobject
org.json.JSONObject.get java code examples | Tabnine
JSONObject expanded = new JSONObject(); while (!toTraverse.isEmpty()) { String current = toTraverse.remove(); JSONObject json = load(current); JSONObject conf = json.getJSONObject(CONF_KEY); Iterator<String> iter = conf.keys(); while (iter.hasNext()) { String key = iter.next(); expanded.put(key, conf.get(key)); JSONArray includes = json.getJSONArray(INCLUDES_KEY); for (int idx = 0; idx < includes.length(); idx++) { String include = resolve(current, includes.getString(idx)); if (traversedFiles.contains(include)) { ... JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - A JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations. Keys are unique Strings that cannot be null. Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject.NULL object. A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and pairs separated by a comma. It has several constructors with which to construct a JSONObject. ... get(String key) – gets the object associated with the supplied key, throws JSONException if the key is not found
🌐
GeeksforGeeks
geeksforgeeks.org › java › working-with-json-data-in-java
Working with JSON Data in Java - GeeksforGeeks
December 23, 2025 - To read and write JSON data in Java, we commonly use third-party libraries.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › json › json_java_example.htm
JSON with Java
Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided.
🌐
GitHub
github.com › stleary › JSON-java
GitHub - stleary/JSON-java: A reference implementation of a JSON package in Java. · GitHub
import org.json.JSONObject; public class Test { public static void main(String args[]){ JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }"); System.out.println(jo); } }
Starred by 4.7K users
Forked by 2.6K users
Languages   Java
🌐
How to do in Java
howtodoinjava.com › home › java libraries › json.simple – read and write json
JSON.simple - Read and Write JSON in Java
October 1, 2022 - JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON. In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-the-values-of-the-different-types-from-a-json-object-in-java
How to get the values of the different types from a JSON object in Java?
Create a JSONObject object and pass the JSON string to it. Use the getString(), getInt(), getDouble(), and getBoolean() methods to extract the values of different types from the JSON object.
🌐
Medium
medium.com › @Mohd_Aamir_17 › mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1
Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson | by Mohd Aamir | Medium
November 4, 2024 - This article offers an in-depth look at how to parse, create, and manipulate JSON objects, arrays, and nodes using the Jackson library, covering advanced scenarios to equip you with the tools to tackle complex JSON data in Java.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods.
🌐
Baeldung
baeldung.com › home › json › jackson › json in java
JSON in Java | Baeldung
May 11, 2024 - Learn how to start working with JSON data in Java.
Top answer
1 of 12
228

Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

package so4308554;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}
2 of 12
74

Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

🌐
DigitalOcean
digitalocean.com › community › tutorials › java-json-example
Java JSON Example | DigitalOcean
August 4, 2022 - javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject. We can get JsonReader from Json class or JsonReaderFactory.
🌐
GeeksforGeeks
geeksforgeeks.org › java › parse-json-java
How to parse JSON in Java - GeeksforGeeks
December 23, 2025 - import java.io.FileReader; import java.util.Iterator; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JSONReadExample { public static void main(String[] args) throws Exception { Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); JSONObject jo = (JSONObject) obj; String firstName = (String) jo.get("firstName"); String lastName = (String) jo.get("lastName"); long age = (long) jo.get("age"); System.out.println(firstName); System.out.println(lastName); System.out.println(age); Ma
🌐
JetBrains
teamcity-support.jetbrains.com › hc › en-us › community › posts › 4408838592530-Get-JSON-from-REST-API-in-Java
Get JSON from REST API in Java – TeamCity Support | JetBrains
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.Iterator; import com.google.gson.Gson; public static void main(String[] args) { String user = "<TEAMCITY USER>"; String pass = "<TEAMCITY USER PASSWORD>"; String TeamCityRestAPIEndpoint = "<TEAMCITY ENDPOINT>"; String usersService = "/users"; TCUserResponse userList = null; try { //Prepare Basic Auth String auth = user + ":" + pass; String encodedAuth = Base64.getE