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
Videos
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
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.
JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.
The jQuery method is now deprecated. Use this method instead:
let jsonObject = JSON.parse(jsonString);
Original answer using deprecated jQuery functionality:
If you're using jQuery just use:
jQuery.parseJSON( jsonString );
It's exactly what you're looking for (see the jQuery documentation).
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; }
}
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
- use Regex to make it a real JSON
- 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);
}