I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson()
. Below is an example of what the string can look like:
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}
In this string every JSON object contains an array of other JSON objects. 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?
Best Answer
Google Gson supports generics and nested beans. The
[]
in JSON represents an array and should map to a Java collection such asList
or just a plain Java array. The{}
in JSON represents an object and should map to a JavaMap
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:Fairly simple, isn't it? Just have a suitable JavaBean and call
Gson#fromJson()
.See also: