JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");
JSONObject name1 = json.getJSONObject("John");
String ageJohn = name1.getString("Age");

For getting those items in a dynamic way:

JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");

for (Iterator key=json.keys();key.hasNext();) {
    JSONObject name = json.get(key.next());
    //now name contains the firstname, and so on... 
}
Answer from Emanuel on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
Returns the string value to which the specified name is mapped. This is a convenience method for (JsonString)get(name) to get the value. ... the string value to which the specified name is mapped, or null if this object contains no mapping for the name
🌐
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 ...
Discussions

java - How to get elements of JSONObject? - Stack Overflow
Now all I know is the object ... , So, is there's a way to parse that Object so that I can get it's elements and deal with it (ie. John, Ross) ? ... What JSON library are you using? There is not (yet) a standard JSON API for Java.... More on stackoverflow.com
🌐 stackoverflow.com
Creating JSON objects directly from model classes in Java - Stack Overflow
I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to exchange objects of these classes as a JSONObject via Socke... More on stackoverflow.com
🌐 stackoverflow.com
Converting JSON data to Java object - Stack Overflow
The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. 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? More on stackoverflow.com
🌐 stackoverflow.com
Is it common that it's so difficult to handle JSON payloads in Java?
No? It's rather easy to work with JSON in Java, but Java remains a statically typed language. If you want to manipulate them dynamically, just deserialize them to a JsonTree-like object and work your way through that. Or maybe even a HashMap. More on reddit.com
🌐 r/java
22
7
December 20, 2019
🌐
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
🌐
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.
Find elsewhere
🌐
Processing
processing.github.io › processing-javadocs › core › processing › data › JSONObject.html
JSONObject
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and ...
🌐
Android Developers
developer.android.com › api reference › jsonobject
JSONObject | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Baeldung
baeldung.com › home › json › jackson › json in java
JSON in Java | Baeldung
May 11, 2024 - JSON-P is a Java API for parsing, building, transforming, and querying JSON messages. Java Specification Request (JSR) 353 proposed the API. JSR 353 aims to develop a Java API to process JSON.
🌐
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.
🌐
Javadoc.io
javadoc.io › static › org.json › json › 20171018 › index.html
JSON in Java 20171018 API
August 15, 2016 - JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
🌐
Json2CSharp
json2csharp.com › code-converters › json-to-pojo
Convert JSON to POJO Objects in Java Online
Convert any JSON to POJO objects in Java online. Json2CSharp is a free parser and converter that will help you generate Java classes from a JSON object and use Jackson librairies to deserialize into a Java class.
🌐
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.
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.

🌐
Reddit
reddit.com › r/java › is it common that it's so difficult to handle json payloads in java?
r/java on Reddit: Is it common that it's so difficult to handle JSON payloads in Java?
December 20, 2019 -

I'm trying to learn and use Java with spring boot to rewrite a service in the current system. The existing service is heavily written in Node and has so many payloads passed between many services in JSON format. Rewriting it now feels so painful.

In Node, handling these JSON format is a breeze. But now that I'm using Java, I'm having a nightmare handling them. I'm using Jackson but I just find myself having to create so many object classes just to handle these JSON payloads. And some of these payloads are often deeply nested and have complicated data, which means I will have write a number of custom serlializers and deserializers.

I have also found that those annotations make these class files (or POJOs) somewhat coupled to the JSON payloads because of the annotations. Whenever another service makes a change to the payload such as changing its fields, I will have even more to change!

After handling the JSON objects, occasionally, I've to further convert them into another type of object which will require mapstructs which is again another hell of annotations and configurations to figure out.

I feel like I'm spending so much time just on the payloads even before I can start on the actual biz logic.

Is it common to be so painful when handling JSON in Java? Or am I missing out something that could have made my life a lot easier?

🌐
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
February 2, 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
🌐
Scijava
javadoc.scijava.org › Micro-Manager-Core › mmcorej › org › json › JSONObject.html
JSONObject
It is similar to the put method ... an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. ... JSONException - If the value is an invalid number or if the key is null. public java.lang.Object ...
🌐
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
🌐
Medium
medium.com › @papapapaya11 › exploring-various-ways-to-handle-jsonobject-in-java-6edef1f0561c
Exploring Various Ways to Handle JSONObject in Java | by Little Miss Brave | Medium
December 2, 2024 - String json = "{\"name\":\"Little ... library by Google for serializing and deserializing JSON. ... Gson.fromJson(String json, Class<T> classOfT) – Converts a JSON string into a Java object....