How To Create Json Tree Structure In Java
DISABLE ADBLOCK
ADBlock is blocking some content on the site
- java - json - gson |
- |
- ( words)
Question
Have a couple questions, using GSON. I have a feeling that GSON might not be what I am looking for in terms of a library that will be able to give me a JSON object that I can use later.
I am reading data from a database to populate a json object that I will later use. The output of the json object should look similar to the json below, which involves parents and children. It forms a small tree based structure:
var json = { id: "1", name: "Joe Smith", data: { "email": "", "phone": "123-123-1233"}, children: [{ id: "Tim Anderson", name: "Tim Anderson", data: { "email": "x@gmail.com", "phone": "123-123-1233" }, children: [] },{ id: "Christopher Johnson", name: "Christopher Johnson", data: { "email": "x@gmail.com", "phone": "123-123-1233" }, children: [] },{ id: "Kate Green", name: "Kate Green", data: { }, children: [{ id: "Gary Jones", name: "Gary Jones", data: {}, children: [] }, { id: "Melissa Brand", name: "Melissa Brand", data: {}, children: [] }] } ] } How do I create a GSON object, similar to the structure above, that I can serialize to JSON that has this type of hierarchy? I've tried using maps and other collections - but I am having difficulty getting the results I want. Hence why I ask if GSON is what I really want for a JSON serialization.
Solution
Let me give you a hint
make a Person and a Data class (POJO) like this
Person String id String name Data data List<Person> children Data String email String phone OTHER TIPS
Have you tried the default java JSONTokener and other similar parsers?
BufferedReader reader = new BufferedReader(new FileReader("jsonfile.json")); StringBuilder builder=new StringBuilder(); for(String line=null;(line = reader.readLine()) != null;){ builder.append(line).append("\n"); } JSONTokener jsonTokener=new JSONTokener(builder.toString()); JSONObject finalJson=new JSONObject(jsonTokener); In your case if you want to find additional data in a hierarchy inside, then iterate over as follows
JSONArray children=finalJson.getJSONArray("children"); for(int i = 0;i<children.length;i++){ JSONObject childRecData = children.getJSONObject(i); //returns the ith JSONObject containing id, name, data, etc. int id = childRecData.getString(); String name = childRecData.getString(); JSONObject data = childRecData.getJSONObject(0); } NOTE That for larger JSON files (files which have ridiculous levels of hierarchy) such as an HTTP database requests GSON's POJO (Plain Old Java Objects) model as suggested by Nishant is recommended
Here's more information
Here was a similar question
How To Create Json Tree Structure In Java
Source: https://www.generacodice.com/en/articolo/4428671/gson-creating-json-tree-structure-from-java
Posted by: gablewhiparinkes54.blogspot.com

0 Response to "How To Create Json Tree Structure In Java"
Post a Comment