简体   繁体   中英

Only last value is getting added to JSON Object

I have a xml file which contains huge data. i have parsed the xml file and trying to add the values to JSON Object but only the last value is getting added.Please find my code below:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Process_Parser {

static JSONObject json= new JSONObject();
//static //JSONObject arrayvalue=new JSONArray();

public static void main(String args[]) {
try {

File process = new File("/Users/instrument.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(process);
doc.getDocumentElement().normalize();

//System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("process");
//System.out.println("==========================");

Element pageElement = (Element)doc.getElementsByTagName("process").item(0);
//NodeList result = pageElement.getElementsByTagName("processName");
System.out.println("Suba-----------"+nodes.getLength());

for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
//System.out.println(getValue("processName", element).contains("carkitd"));
//if(element.getElementsByTagName("process") != null){
if(element.getFirstChild().getNodeValue() != null){
    if(getValue("processName", element).contains("carkitd")){


        json.put("processName",getValue("processName", element));
        json.put("cpuUsage",getValue("cpuUsage", element));
        json.put("realmemory",getValue("realmemory", element));
        json.put("Virtualmemory",getValue("Virtualmemory", element));
        json.put("thread",getValue("thread", element));
        json.put("cputime",getValue("cputime", element));

}
}   

}
} 
//System.out.println("result-array:" +arrayvalue);
System.out.println("result" +json);
//}
//System.out.println("arrayvalue::"+arrayvalue.size());
}catch (Exception ex) {
ex.printStackTrace();
}
}


private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}

}

When I run the above code I get the below result

Actual Result:

{

"Virtualmemory":"1100320.000000",
"cpuUsage":"0.000000",
"process":"carkitd",
"realmemory":"1044.000000",
"thread":"2.000000",
"cputime":"0.000000"
}

Expected Result:

It is supposed to have 67 objects

Sample xml file:

<instrument>
    <slice time ='1498215480919'>
        <process>
            <processId>1.000000</processId>
            <processName>launchd</processName>
            <cpuUsage>0.203195</cpuUsage>
            <realmemory>5084.000000</realmemory>
            <Virtualmemory>1080112.000000</Virtualmemory>
            <thread>7.000000</thread>
            <cputime>0.000000</cputime>
        </process>
        <process>
            <processId>24.000000</processId>
            <processName>carkitd</processName>
            <cpuUsage>0.002845</cpuUsage>
            <realmemory>576.000000</realmemory>
            <Virtualmemory>1074752.000000</Virtualmemory>
            <thread>6.000000</thread>
            <cputime>0.000000</cputime>
        </process>
        <process>
            <processId>24.000000</processId>
            <processName>carkitd</processName>
            <cpuUsage>0.002845</cpuUsage>
            <realmemory>576.000000</realmemory>
            <Virtualmemory>1074752.000000</Virtualmemory>
            <thread>6.000000</thread>
            <cputime>0.000000</cputime>
        </process>
    </slice>
    </instrument>

Am I missing out something?

Create a JSONArray and keep inserting your JSONObject inside the loop.

 JSONArray finalArray = new JSONArray(); // create your jsonarray
 for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);

     if (node.getNodeType() == Node.ELEMENT_NODE) {
         Element element = (Element) node;
         //System.out.println(getValue("processName", element).contains("carkitd"));
         //if(element.getElementsByTagName("process") != null){
         if (element.getFirstChild().getNodeValue() != null) {
             if (getValue("processName", element).contains("carkitd")) {
                 JSONObject json = new JSONObject(); // your temp obj

                 json.put("processName", getValue("processName", element));
                 json.put("cpuUsage", getValue("cpuUsage", element));
                 json.put("realmemory", getValue("realmemory", element));
                 json.put("Virtualmemory", getValue("Virtualmemory", element));
                 json.put("thread", getValue("thread", element));
                 json.put("cputime", getValue("cputime", element));
                 finalArray.put(json); // push your values in the array
             }
         }

     }
 }
 //System.out.println("result-array:" +arrayvalue);
 System.out.println("result " + finalArray);

You're writing :

json.put("processName",getValue("processName", element));
json.put("cpuUsage",getValue("cpuUsage", element));
json.put("realmemory",getValue("realmemory", element));
json.put("Virtualmemory",getValue("Virtualmemory", element));
json.put("thread",getValue("thread", element));
json.put("cputime",getValue("cputime", element));

Jus tlike a Map , this override the value if it's already present. At every iteration, you just override your JSON object.

You should create a new JSONObject every iteration and store it in a JSONArray .

You can refer to my question here for easier implementation.

You can use JSON-java library by stleary.

You can use the following code to convert an XML string into JSONObject.

JSONObject data = XML.toJSONObject(xmlString);

You can find more info about it here: JSON-java

With the above reference, I am able to implement the solution at least.I hope this will work for others as well.

private static JSONObject extractData(NodeList nodeList, String tagName) throws TransformerConfigurationException,
        TransformerException, TransformerFactoryConfigurationError, JSONException {
    JSONObject resultObject = new JSONObject();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (!node.getNodeName().equals(tagName) && node.hasChildNodes()) {
            return extractData(node.getChildNodes(), tagName);
        } else if (node.getNodeName().equals(tagName)) {
            DOMSource source = new DOMSource(node);
            StringWriter stringResult = new StringWriter();
            TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult));
            resultObject = XML.toJSONObject(stringResult.toString()).optJSONObject(tagName);
        }
    }
    return resultObject;
}

public static JSONObject getFullData(String tagName, SOAPMessage message) throws Exception {
    NodeList nodeList = message.getSOAPBody().getChildNodes();
    JSONObject resultObject = extractData(nodeList, tagName);
    return resultObject;
}

For your case just initialize json inside the loop

json = new JSONObject();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM