Sunday, 28 September 2014

Obtaining elements and attributes from JSONArray using Java



I have the following JSONArray:



[
{
"test":{
"page":"Apple",
"ms":"234"}
},
{
"check":{
"page":"Apple",
"ms":"234"
}
}
]


Here say "test" and "check" are the parent elements and there will be quite a lot of elements like this. So i have to loop through each and every one of them and have to get the child element of the if it matches the name. Im so new to JSON, so have no idea how it works. Below is the simple algorithm how it should work.



Loop through each elements:
switch(parent_name){
case "test":
get child information like:
if(attribute == "page"){
get text which is "Apple"
}
break;
default:
break;
}


This is how it should work. I have tried in XML. But not JSON. Below is the xml code:



Element docEle = doc.getDocumentElement();
NodeList nl = docEle.getChildNodes();

if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element ele = (Element) nl.item(i);
switch(ele.getNodeName()){
case "Click":
ele.getAttributes().getNamedItem("object").getNodeValue();
break;
case "Open":
ele.getAttributes().getNamedItem("page").getNodeValue();
break;
case "CheckElementPresent":
ele.getAttributes().getNamedItem("object").getNodeValue();
break;
default:
break;
}
}
}
}

No comments:

Post a Comment