There is @JsonType annotation which allows to serialize the type into property:

@JsonTypeInfo(
   use = JsonTypeInfo.Id.NAME, 
   include = JsonTypeInfo.As.PROPERTY, 
   property = "type")
@JsonSubTypes({ 
   @Type(value = Person.class, name = "Person"), 
   @Type(value = Role.class, name = "Role") 
   // ...
 })
 public abstract class Individual {
    // ...
 }
Answer from Zbynek Vyskovsky - kvr000 on Stack Overflow
Discussions

Newest Questions - Stack Overflow
Stack Overflow | The World’s Largest Online Community for Developers More on stackoverflow.com
🌐 stackoverflow.com
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
Converting JSON data to Java object - Stack Overflow
-1 I am getting the json data from client,i want convert that json data into java object and store into db 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
🌐
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.
🌐
YouTube
youtube.com › retarget common
41.Convert dynamic JSON Response to Java Object to extract values in Rest Assured - YouTube
Hey Guys,We have learned to deserialize JSON responses to Java Map and List in the last two video tutorials. But if we are not sure of the type of API respon...
Published: June 5, 2021
Views: 12K
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

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.

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 - We can treat this kind of structure as a dynamic object. Unfortunately, this means we can’t define common properties, we have to treat them dynamically, too. Alternatively, we could use @JsonAnySetter to mark a method for handling additional, unknown properties.
🌐
Attacomsian
attacomsian.com › blog › jackson-map-dynamic-json-object
How to map a dynamic JSON object with Jackson
October 14, 2022 - We want to find an appropriate way to map this address property to a User object. The most straightforward way of mapping dynamic JSON properties is to use the JsonNode class provided by Jackson.
🌐
JSONLint
jsonlint.com › json-to-java
JSON to Java Converter - Generate POJO Classes Online | JSONLint
This tool automatically generates Java class definitions from your JSON data. It infers types from values, handles nested objects, and supports popular libraries like Lombok, Jackson, and Gson.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 515751 › convert-json-input-into-java-objects
database sql - Convert json input into java objects | DaniWeb
March 2, 2018 - Practical, reliable patterns are: parse JSON into a generic tree or map (Jackson's JsonNode, Gson's JsonElement or Map<String,Object>), persist the raw JSON in a JSON/JSONB column, or—only when necessary—generate runtime types (ByteBuddy/Javassist). Runtime class generation is possible but adds complexity and maintenance cost. A common, pragmatic approach is to walk a generic tree and build SQL dynamically while using prepared statements for values.
🌐
Reddit
reddit.com › r/json › how to dynamically map json fields to java class
r/json on Reddit: How to dynamically map JSON fields to Java class
October 19, 2023 -

I have a json payload like below, currently I have a POJO class that have the mappings of the json fields. I am getting this json payload from a 3rd party client and the fields may change in the future. My question is how can I map them dynamically so that my code won't break?

Sample json:
{ "CUSTOMERID": "123456", "firstName": "test1", "middleName": "", "lastName": "last2", "suffix": "Mr.", "fullName": " John", "companyName": "IT", "SSN": ""}

The problem is if in future if they change the CUTOMERID to MEMBERID then my code would fail. How to overcome this?

🌐
YouTube
youtube.com › random code
How to convert JSON to Java objects using Gson - YouTube
Working with JSON in hJava can be a struggle I therefore wanted to showcase my preferred library Gson making this process quite a bit simpler.Code: https://g...
Published: August 17, 2023
Views: 1K
🌐
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 - A JSON Object is a collection of key-value pairs, similar to a Map in Java. Jackson's ObjectMapper can convert JSON strings into Java objects or JsonNode instances, giving you flexible access to JSON data without predefined classes.
🌐
Medium
kgstrivers.medium.com › json-to-object-using-object-mapper-88379d722d2b
JSON to object using Object Mapper | by Kaushik Ghosh | Medium
March 18, 2024 - Java · Json To Object · System Design · Kaushik Ghosh · Follow · 2 min read · ·Mar 18, 2024 · 1 · 1 · Listen · Share · Press enter or click to view image in full size · JSON to object using Object Mapper · Object Mapper is a main ...
🌐
Stack Abuse
stackabuse.com › how-to-convert-json-object-to-java-object-with-jackson
How to Convert JSON Object to Java Object with Jackson
February 27, 2023 - To convert a JSON object into a Java object, you'll use the readValue() method of the ObjectMapper instance, which deserializes it into the provided class reference:
🌐
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.
🌐
Baeldung
baeldung.com › home › json › jackson › intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - This tutorial focuses on understanding the Jackson ObjectMapper class and how to serialize Java objects into JSON and deserialize JSON string into Java objects.