I need to Parse a JSON in java to a hash map. I tried a method by giving its tag name and attributes. While I need a generic version which will parse all attributes of the first child element of root element to a hash map.
I tried this code
public static void main() {
Map<String, String> map = new HashMap<String, String>();
String cfgXml = "<response><result code=\"0\" whatever=\"Whatever\"/></response>";
try
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(cfgXml)));
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("result");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
Config c = new Config();
c.code = eElement.getAttribute("code");
c.whatever = eElement.getAttribute("whatever");
if(!map.containsKey(c.code)){
map.put("code", c.code);
map.put("whatever", c.whatever);
}
System.out.println(map);
}
}
for (String name: map.keySet()){
String key =name.toString();
String value = map.get(name).toString();
/*** Key value will be output here **/
System.out.println(key + "->" + value);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class Config
{
@Override
public String toString()
{
return "Result [code=" + code + ", whatever=" + whatever + "]";
}
public String code;
public String whatever;
}
Here I get the output, But here I am taking the tag name as result and attributes are also given. I need a generic function, I won't be knowing the tag name and attributes, It will be different in different XML string!
Any help will be appreciated
XML file can be :
<response>
<balance balance=”1000000” overdraft=”0”/>
</response>
OR
<response>
<result code=”0”/>
</response>
It can change!!