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
Answer from BalusC on Stack Overflow
🌐
Medium
davutgurbuz.medium.com › the-need-history-c91c9d38ec9
Creating Java classes from JSON dynamically. | by Davut Gürbüz | Medium
June 1, 2020 - There are libraries serializing JSON objects to known classes in many programming languages, jackson is the dominant one in Java and JSON.NET is the popular one in .net stack. There are even some websites converting JSON to Java or C# online. If you check these sites, you’ll figure out they create java classes either from a backend service or by using javascript directly.
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.

Discussions

Parse Dynamic JSON to Object in Java - Stack Overflow
I have a weird JSON which has Dynamic Object Name. Something like this · { "Sample_01": { "class": "Tenant", "A1": { "class": "Application", "template": "http" } }, "Sample_02": { "class": "Tenant", "A2": { "class": "Application", "template": "http" } } } Here Sample_01 and Sample_02 are dynamic and this value can be anything. Same goes from A1 and A1 attr. ... I am using GSON. Can also use any other way as long as it's in Java... More on stackoverflow.com
🌐 stackoverflow.com
java - How to convert Json String with dynamic fields to Object? - Stack Overflow
As far as I am aware, I think you will need to have some mappings defined somewhere (I used xml's) and then try to match json with one of the mappings to create objects. Google gson is good. I did it in Jackson · Also, converting objects should be trivial. More on stackoverflow.com
🌐 stackoverflow.com
How do I transform a dynamic json to java class? - Stack Overflow
But now I wanted to have dataPair to be dynamic so whatever key-value pair we receive we will able to get it without changing the class. I was wondering how should I change dataPair class or is there a way to generate key-value pair fields? ... I'd recommend using Jackson library to serialize Java to JSON and back: mvnrepository.com/artifact/com.fasterxml.jackson.core/… ... Could you use Retrofit 2.0? https://square.github.io/retrofit/ It easy works with converting ... More on stackoverflow.com
🌐 stackoverflow.com
How to convert the following json string to java object? - Stack Overflow
It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
4

You can use JSONObject from http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar

public static void main(String[] args) {
        String input="{\r\n" + 
                "    \"Sample_01\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A1\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    },\r\n" + 
                "    \"Sample_02\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A2\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    }\r\n" + 
                "}";

        JSONObject jsonObject = new JSONObject(input);  


        Set<String> keys =jsonObject.keySet();
        for(String key:keys) {
            System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
        }
    }

If you again wants to parse the value of Sample_01 or Sample_02 or Sample_XX Check the instance of jsonObject like if(jsonObject.get(key) instanceof JSONObject) and Reiterate the loop

2 of 2
2

Extending the answer added by @Deepak. Both approaches are feasible but I preferred Gson as I was already using it.

Using JSONObject

JSONObject jsonObject = new JSONObject(input);  


Set<String> keys =jsonObject.keySet();
for(String key:keys) {
    System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
}

Using Gson

public static void main(String[] args) {
        
    String json = "{\"Sample_01\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.0.1.10\"],\"pool\":\"web_poolddd\"},\"web_poolddd\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.13.10\",\"192.0.14.11\"]}]}}},\"Sample_20\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.2.2.2\"],\"pool\":\"web_pool_data\"},\"web_pool_data\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.10.10\",\"192.0.10.11\"]}]}}}}";
    
    Type listType = new TypeToken<Map<String, Object>>(){}.getType();
    Gson gson = new Gson();
    Map<String,Object> myList = gson.fromJson(json, listType);

    JsonParser parser = new JsonParser();

    for (Map.Entry<String,Object> m : myList.entrySet())
    {
        System.out.println("==============");
        if(m.getValue() instanceof String){
            // get String value
        }else{ // if value is an Object
            
            System.out.println("VIP Sec: Name: "+m.getKey());
            Map<String,Object> myList1 = gson.fromJson(m.getValue().toString(), listType);
            for (Map.Entry<String,Object> m1 : myList1.entrySet())
            {
                if(!( m1.getValue() instanceof String)){
                    Map<String,Object> myList2 = gson.fromJson(m1.getValue().toString(), listType);
                    for (Map.Entry<String,Object> m2 : myList2.entrySet())
                    {
                         if(!( m2.getValue() instanceof String)){
                            Map<String,Object> myList3 = gson.fromJson(m2.getValue().toString(), listType);
                            for (Map.Entry<String,Object> m3 : myList3.entrySet())
                            {
                                if(m3.getKey().equals("virtualAddresses")){
                                    System.out.println("VIP Sec: IP Address: "+m3.getValue());
                                }
                                else if(m3.getKey().equals("pool")){
                                    System.out.println("Pool Sec: Name: "+m3.getValue());
                                }else if(m3.getKey().equals("monitors")){
                                    JsonArray monitors = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < monitors.size()){
                                        String monitor = monitors.get(count).getAsString();
                                        System.out.println("Monitor: "+monitor);
                                        count++;
                                    }
                                }else if(m3.getKey().equals("members")){
                                    JsonArray members = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < members.size()){
                                        // Parsing as Object to key values by key directly
                                        JsonObject mem = members.get(count).getAsJsonObject();
                                        String port = mem.get("servicePort").getAsString();
                                        System.out.println("Port: "+port);
                                        JsonElement ipAddrs = mem.get("serverAddresses");
                                        if(ipAddrs.isJsonArray()){
                                            JsonArray ips = ipAddrs.getAsJsonArray();
                                            int c = 0;
                                            while(c < ips.size()){
                                                String ip = ips.get(c).getAsString();
                                                System.out.println("IP: "+ip);
                                                c++;
                                            }
                                        }
                                        count++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



OUTPUT:

==============
VIP Sec: Name: Sample_01
VIP Sec: IP Address: [10.0.1.10]
Pool Sec: Name: web_poolddd
Monitor: http
Port: 80.0
IP: 192.0.13.10
IP: 192.0.14.11
==============
VIP Sec: Name: Sample_20
VIP Sec: IP Address: [10.2.2.2]
Pool Sec: Name: web_pool_data
Monitor: http
Port: 80.0
IP: 192.0.10.10
IP: 192.0.10.11

Read more about 2nd approach here

🌐
Jsonschema2pojo
jsonschema2pojo.org
jsonschema2pojo
Generate Plain Old Java Objects from JSON or JSON-Schema.
🌐
Attacomsian
attacomsian.com › blog › jackson-map-dynamic-json-object
How to map a dynamic JSON object with Jackson
October 14, 2022 - A short tutorial to learn how to map a dynamic JSON object to a Java class using Jackson API.
Find elsewhere
🌐
Baeldung
baeldung.com › home › json › jackson › mapping a dynamic json object with jackson
Mapping a Dynamic JSON Object with Jackson | Baeldung
January 8, 2024 - Working with predefined JSON data structures with Jackson is straightforward. However, sometimes we need to handle dynamic JSON objects, which have unknown properties. In this quick tutorial, we’ll learn multiple ways of mapping dynamic JSON objects into Java classes.
🌐
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.
🌐
Code Beautify
codebeautify.org › json-to-java-converter
JSON to JAVA Converter: Convert JSON to JAVA Class
This tool will help you to convert your JSON String/Data to JAVA Class Object.
🌐
Site24x7
site24x7.com › tools › json-to-java.html
JSON to JAVA Code Generator: Site24x7 Tools
Free code generator which converts your JSON (JavaScript Object Notation) schema into Java Object. The JSON keys are converted to private variables with getter setter methods for them. The inner objects in JSON are converted as inner classes in Java Object.
🌐
Minifier
minifier.org › json-to-java
Convert JSON to Java Object Online
JSON to Java Converter effortlessly converts JSON data into Java class objects with a single click.
🌐
JSON Formatter
jsonformatter.org › json-to-java
Best JSON to Java Converter
JSON to Java Online with https and easiest way to convert JSON to Java. Save online and Share.
🌐
Blogger
javarevisited.blogspot.com › 2022 › 03 › 3-examples-to-parse-json-in-java-using.html
3 ways to parse JSON String to Object in Java [Jackson, Gson, and json-simple Example]
April 22, 2023 - You just need to use the ObjectMapper class, which provides the readValue() method. This method can convert JSON String to Java object, that's why it takes JSON as a parameter and the Class instance in which you want to parse your JSON.
🌐
Medium
medium.com › backend-habit › easy-step-to-convert-json-into-java-object-f4ef64e5aa11
Easy step to convert JSON into Java Object | by Teten Nugraha | Backend Habit | Medium
September 2, 2021 - Java is a static language different from scripting languages such as PHP, Javascript which can easily transform json messages, but Java itself needs a special trick so that these requirements are met. ... <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> You can get it with this link https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.12.4 · Here is the json file that we will use, in this case we will transform the json person into a person object