Consider I have a JSON string of the following format:
How do I parse this using Gson so that I can write a method to perform actions based on individual occurrences of the values and their parents?
Here’s a sample JSON string, however, consider the actual JSON string to be much more complex one consisting of deeply nested subarrays.
A sample one:
[{"Name":"First","Parent":"none","Elements":[{"One": 1, "Two": 2,"Parent":"none"}]},
{"Name":"Second","Parent":"First","Elements":"none"},
{"Name":"Third","Parent":"Second","Elements":"none"},
{"Name":"Fourth","Parent":"Eighth","Elements":[{"One": 1, "Two": 2,"Parent":"Tenth"}]},
{"Name":"Fifth","Parent":"none","Elements":[{"One": 1, "Two": 2,"Parent":"First"}]},
{"Name":"Sixth","Parent":"Fourth","Elements":[{"One": 1, "Two": 2,"Parent":"First"}]},
{"Name":"Seventh","Parent":"Sixth","Elements":[{"One": 1, "Two": 2,"Parent":"Ninth"}]},
{"Name":"Eighth","Parent":"Seventh","Elements":[{"One": 1, "Two": 2,"Parent":"Tenth"}]},
{"Name":"Ninth","Parent":"Fourth","Elements":[{"One": 1, "Two": 2,"Parent":"Eighth"}]},
{"Name":"Tenth","Parent":"Third","Elements":[{"One": 1, "Two": 2,"Parent":"Second"}]},
{"Name":"Eleventh","Parent":"First","Elements":[{"One": 1, "Two": 2,"Parent":"First"}]}]
Perhaps not the answer sought:
Gson does not currently have a built in mechanism to handle bi-directional references, during serialization or deserialization (except that for serialization fields in children referencing parents can be selectively excluded*, with the resulting JSON then lacking the parent reference data in the child, or custom serialization processing can replace the parent reference with a new JSON element, and for deserialization, it’s possible to implement custom processing along the lines M.J. described).
Jackson does.
*The mechanism to exclude a field from serialization is to actually specify that all of the other fields should be included. See the @Expose documentation for details.