org.json.JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
Answer from srain on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › working-with-json-data-in-java
Working with JSON Data in Java - GeeksforGeeks
December 23, 2025 - It is easy to read, write, and ... in key–value pairs and supports arrays and nested objects. Example: Storing student information in JSON format....
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-json-example
Java JSON Example | DigitalOcean
August 4, 2022 - Streaming API - It’s similar to StaX Parser and good for large objects where you don’t want to keep whole object in memory. ... javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject.
🌐
TutorialsPoint
tutorialspoint.com › json › json_java_example.htm
JSON with Java
The following example makes use of JSONObject and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List. import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; class JsonDecodeDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; try{ Object obj = parser.parse(s); JSONArray array = (JSONArray)obj; System.out.pr
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - One of JSONObject’s constructors takes a POJO as its argument. In the example below, the package uses the getters from the DemoBean class and creates an appropriate JSONObject for the same. To get a JSONObject from a Java Object, we’ll have to use a class that is a valid Java Bean:
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using JsonReader.readObject(). For example:
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
For example, given a JSONObject initialized with this document: ... "/a/b" Then this method will return the String "c". A JSONPointerException may be thrown from code called by this method. ... Queries and returns a value from this object using jsonPointer, or returns null if the query fails ...
🌐
CodeSignal
codesignal.com › learn › courses › handling-json-files-with-java › lessons › creating-and-writing-json-data-with-java-using-jackson
Creating and Writing JSON Data with Java
Serialize to JSON: Use the Jackson library's ObjectMapper class to serialize these objects into a JSON string, ready for storage or transmission. These steps form the foundation of translating structured class-based data into a JSON format, seamlessly bridging Java applications with JSON data handling.
Find elsewhere
🌐
Javatpoint
javatpoint.com › java-json-example
Java JSON Example
Java JSON example for beginners and professionals with examples of JSON with java, install json.simple, java json encode, java json encode using map, java json array encode, java json array encode using List, java json decode. Learn Java JSON example with array, object, schema, encode, decode, file, date etc.
🌐
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 - You are dealing with dynamic or nested structures, where some fields may be arrays, while others are objects or primitives. You need a flexible approach to handle JSON without strict adherence to a particular structure. In essence, ArrayNode is suitable for structured JSON arrays, while JsonNode is ideal for complex, dynamic JSON processing. One of Jackson’s strongest features is its ability to easily convert JSON data into Java objects, and vice versa.
🌐
Processing
processing.github.io › processing-javadocs › core › processing › data › JSONObject.html
JSONObject
August 4, 2020 - This is the most commonly used JSONObject constructor. ... Get the value object associated with a key. ... The object associated with the key. ... A string which is the value. ... Get an optional string associated with a key. It returns the defaultValue if there is no such key. ... A string which is the value. ... The integer value. ... java.lang.RuntimeException - if the key is not found or if the value cannot be converted to an integer.
🌐
iO Flood
ioflood.com › blog › jsonobject-java-class
Java's JsonObject Class: A Detailed Exploration
February 2, 2023 - Here’s an example where a person has multiple phone numbers, represented as a JSON array: import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; public class Main { public static void main(String[] args) { JsonArray ...
🌐
LabEx
labex.io › tutorials › java-how-to-use-jsonobject-in-java-420803
How to use JSONObject in Java | LabEx
November 26, 2022 - Learn efficient JSON manipulation techniques in Java using JSONObject, covering parsing, creating, and transforming JSON data with practical code examples and best practices.
🌐
Oracle
docs.oracle.com › javaee › 7 › tutorial › jsonp001.htm
19.1 Introduction to JSON - Java Platform, Enterprise Edition: The Java EE Tutorial (Release 7)
December 20, 2019 - JSON is a text-based data exchange format derived from JavaScript that is used in web services and other connected applications. The following sections provide an introduction to JSON syntax, an overview of JSON uses, and a description of the most common approaches to generate and parse JSON. JSON defines only two data structures: objects ...
🌐
Oracle
docs.oracle.com › javame › 8.0 › api › json › api › com › oracle › json › JsonObject.html
JsonObject (JSON Documentation)
The map object's iteration ordering is based on the order in which name/value pairs are added to the corresponding builder or the order in which name/value pairs appear in the corresponding stream. ... clear, containsKey, containsValue, entrySet, equals, get, hashCode, isEmpty, keySet, put, putAll, remove, size, values ... Returns the array value to which the specified name is mapped. This is a convenience method for (JsonArray)get(name) to get the value. ... the array value to which the specified name is mapped, or null if this object contains no mapping for the name ... java.lang.ClassCastException - if the value to which the specified name is mapped is not assignable to JsonArray type
🌐
GitHub
github.com › stleary › JSON-java
GitHub - stleary/JSON-java: A reference implementation of a JSON package in Java. · GitHub
The unit tests can be executed ... ... 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
🌐
Medium
medium.com › @benpourian › how-to-create-a-java-object-from-a-json-object-c47c08b030c5
How to create a Java Object from a JSON object | by Benjamin Pourian | Medium
October 25, 2018 - This will be a very brief guide to creating a Java object from a JSON object using the popular gson` google library. I will first demonstrate a simple JSON → POJO example then follow that with another example where I will be using annotations provided by gson to instantiate a new object by ...
🌐
Crunchify
crunchify.com › json tutorials › how to parse jsonobject and jsonarrays in java? beginner’s guide
How to Parse JSONObject and JSONArrays in Java? Beginner's Guide • Crunchify
April 14, 2023 - Here is a simple Java tutorial which demonstrate how to parse JSONObject and JSONArrays in Java. JSON syntax is a subset of the JavaScript object notation
Top answer
1 of 15
371

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }
    
    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

See also:

  • Json.org - Introduction to JSON
  • Gson User Guide - Introduction to Gson
2 of 15
52

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.