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
๐ŸŒ
ConvertSimple
convertsimple.com โ€บ convert-json-to-javascript
Convert JSON to Javascript Object Online - ConvertSimple.com
October 17, 2020 - Paste your JSON input into the left input box and it will automatically convert it into JavaScript Object. The JavaScript Object output is the box to the right.
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.

๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ JSON โ€บ stringify
JSON.stringify() - JavaScript - MDN Web Docs
Boolean, Number, String, and BigInt (obtainable via Object()) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. Symbol objects (obtainable via Object()) are treated as plain objects.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ converting-json-text-to-javascript-object
Converting JSON text to JavaScript Object - GeeksforGeeks
July 11, 2025 - Each key-value pair inside braces are separated by comma (, ). JSON object looks something like this : ... JSON text/object can be converted into Javascript object using the function JSON.parse().
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ JSON โ€บ parse
JSON.parse() - JavaScript - MDN Web Docs
The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
๐ŸŒ
Json2CSharp
json2csharp.com โ€บ code-converters โ€บ json-to-pojo
JSON to POJO Object Online Converter - Json2CSharp Toolkit
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.
Find elsewhere
๐ŸŒ
JSON Editor Online
jsoneditoronline.org
JSON Editor Online: edit JSON, format JSON, query JSON
JSON Editor Online is the original and most copied JSON Editor on the web. Use it to view, edit, format, repair, compare, query, transform, validate, and share your JSON data.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_json_parse.asp
JSON.parse()
You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ javascript โ€บ x1ezvres โ€บ javascript-object-to-json-example
How do I convert object to JSON in JavaScript?
When converting a JavaScript object to JSON with the JSON.stringify(value, replacer, space) method, you can use the "replacer" function to alter the resulting JSON.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_json_stringify.asp
JSON.stringify()
You can convert the string back into a date object at the receiver. In JSON, functions are not allowed as object values.
๐ŸŒ
HTML Code Generator
html-code-generator.com โ€บ javascript โ€บ json-to-object
JSON To JavaScript Object Converter Online | Free Tool
In this example, a JSON string is parsed into a JavaScript object, allowing you to access its properties using dot notation. Use JSON.parse() to convert JSON to a JavaScript object.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ how-to-convert-json-to-javascript-object
How to Convert JSON to JavaScript Object
October 27, 2023 - In this guide, learn how to convert a JSON string to a JavaScript object or array using JSON.parse().
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ powershell โ€บ module โ€บ microsoft.powershell.utility โ€บ convertfrom-json
ConvertFrom-Json (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
The Raw parameter returns the whole file as a single JSON object. Then it uses the pipeline operator to send the delimited string to the ConvertFrom-Json cmdlet, which converts it to a custom object.
๐ŸŒ
Js2ts
js2ts.com โ€บ js-object-to-json
Convert JavaScript Object to JSON Online | JS to JSON Converter js2ts.com
This online converter harnesses AI to seamlessly convert your Javascript Object code to JSON code in just a click of a button.
๐ŸŒ
Json2CSharp
json2csharp.com
Convert JSON to C# Classes Online - Json2CSharp Toolkit
JSON: { 'test-test' : 'test'} C#: [JsonProperty("test-test")] public string testtest { get; set; } ... Add the NullValueHandling.Ignore attribute in case you have null values and want to serialize the object while ignoring properties with null values:
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ c# โ€บ how to turn an object into a json string in c#
How to turn an object into a JSON string in C# | Sentry
To convert a JSON string back to an object, run deserialize, specifying the class you want to convert the string to:
Top answer
1 of 3
4

If you can't fix the JSON document you can create a custom JSON type converter and apply it to the style property. And whoever created that document needs to fix their bug.

If you use System.Text.Json, a possible converter could be :

public class StyleStringJsonConverter : JsonConverter<Style>
{
    public override Style Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) =>
            JsonSerializer.Deserialize<Style>(reader.GetString()!);

    public override void Write(
        Utf8JsonWriter writer,
        Style style,
        JsonSerializerOptions options) =>
            writer.WriteStringValue(JsonSerializer.Serialize(style));
}

This can be applied through an attribute :

public class Root
{
    public string lng_x { get; set; }
    [JsonConverter(typeof(StyleStringJsonConverter))]
    public Style style { get; set; }
}

JSON.NET also has custom converters:

public class StyleStringConverter : JsonConverter<Style>
{
    public override void WriteJson(JsonWriter writer, Style value, JsonSerializer serializer)
    {
        writer.WriteValue(JsonConvert.SerializeObject(value));
    }

    public override Style ReadJson(JsonReader reader, Type objectType, Style existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        string s = (string)reader.Value;

        return JsonConvert.DeserializeObject<Style>(s);
    }

}

This can be applied using an attribute too:

public class Root
{
    public string lng_x { get; set; }
    [JsonConverter(typeof(StyleStringJsonConverter))]
    public Style style { get; set; }
}
2 of 3
0

As stated before, the original creators should fix your the JSON file. Meanwhile, you are stuck with it.

To make sure you don't dirty your own code

  1. use Regex to make it a real JSON
  2. Deserialize as normal

Advantage: When the JSON is changed to a correct form you have to remove the CleanJSON Method and your code will stay working.

The Code

using System.Text.Json;
using System.Text.RegularExpressions;

function YourFunction(){
    //-- Get your JSON in string format (from API, file,...)
    string _jsonString = ... ;
    CleanJSON(_jsonString);
    YourModels.Root _correctStructure = (JsonSerializer.Deserialize<YourModels.Root>(_JSsonString);
}

function CleanJSON(string jsonString){
    //__ Probably you can group the regex
    string _regexPatternRoot = @"(\\"")(.*?)(\\)";
    string _regexReplacementRoot = @"""$2";
    string _regexPatternStyle = "\"({)\"(.*?)\"}\"";
    string _regexReplacementStyle = @"$1""$2""}";

    _JSsonString = Regex.Replace(_JSsonString, _regexPatternRoot, _regexReplacementRoot);
    _JSsonString = Regex.Replace(_JSsonString, _regexPatternStyle, _regexReplacementStyle);
}
๐ŸŒ
Parseplatform
community.parseplatform.org โ€บ client sdks โ€บ javascript sdk
Convert JSON to Parse.Object using fromJSON
February 25, 2022 - Iโ€™m trying to convert my Parse object thatโ€™s in JSON format into a Parse.Object using the Parse.Object.fromJSON() and while itโ€™s working for my highest level object, itโ€™s not working for nested objects. I am trying to convert my Products which has a nested pointer of Store and ...