I write an application which creates a JSON File following the below structure:
{
identifier:"id",
label:"name",
items:[
{
id:"ROOT",
name:"Parent1",
type:"ROOT",
children:[
{
_reference:"CHILD1"
}
]
},
{
id:"CHILD1",
name:"Parent1-Child1",
type:"Child",
children:[
{
_reference:"CHILD2"
}
]
},
{
id:"CHILD2",
name:"Child1-Child2",
type:"Child",
children:[
{
_reference:"Child3"
},
{
_reference:"Child4"
}
]
},
{
id:"Child3",
name:"Child2-Child3",
type:"GrandChild"
},
{
id:"Child4",
name:"Child2-Child4",
type:"GrandChild"
},
]
}
So my application actually gets following data for each node of this JSON Tree
PID– It to which i have to attach the child node
CID– ID of Child Node
CNAME– Child Node Name
CTYPE– Child Type
So currently what i am doing is searching the PID in the json file through iterating ( on file system) and once i find the String which has id=PID,i append a Child Ref to that Node
{
_reference:"CHILD-NEXT"
}
and then after this line adding the whole new child node
{
id:"CHILD-NEXT",
name:"Parent1-ChildNext",
type:"Child",
},
But this is very inefficient solution because of iterating the file every time to search the parent node and appending/inserting the child.
So i am looking for a kind of solution in which i just create this JSON structure in memory and when i am done with adding all the nodes then i can write it to the file. I am doing this in JAVA,so i am looking for some existing JSON Libraries which i can use to fulfil this requirement.
Please comment if you need any other information of the above explanation is not clear.
You can use the org.json library to do this.
You first need to read your json file into a
JSONObjectwhich is basically made up of key/value pairs and arrays. You can then loop over the items in the object, look for a pid and add a new child.Here is some sample code to get you started: