ryanmattscott ryanmattscott - 6 months ago 11
Java Question

Ordered JSON conversion in Java, Reading a JSONArray of JSONObjects

I'm sending the following JSON to a Java Program. I put in this configuration so that my order would be preserved. I'm using the org.json library.

"Ordered JSON"

var obj = {
"params":
[
{"base_s" : robot.base.length},
{"base_k" : robot.base.k},
{"base_phi" : robot.base.phi},
{"mid_s" : robot.mid.length},
{"mid_k" : robot.mid.k},
{"mid_phi" : robot.mid.phi},
{"tip_s" : robot.tip.length},
{"tip_k" : robot.tip.k},
{"tip_phi" : robot.tip.phi}
]
};


Before I had the JSON formatted as such:
Original JSON

var obj = {
base_s : robot.base.length,
base_k : robot.base.k,
base_phi : robot.base.phi,
mid_s : robot.mid.length,
mid_k : robot.mid.k,
mid_phi : robot.mid.phi,
tip_s : robot.tip.length,
tip_k : robot.tip.k,
tip_phi : robot.tip.phi
};


The following Java code interpreted the original JSON fine, but has issues with the "Ordered" JSON.

JSONArray nameArray = jsonData.names();
JSONArray valArray = jsonData.toJSONArray(nameArray);


The nameArray is
["items"]
and the valArray is
[[{"base_s":0.314},{"base_k":0.0012},{"base_phi":0.436},{"mid_s":0.314},{"mid_k":0.0012},{"mid_phi":0.436},{"tip_s":0.3139},{"tip_k":0.0012},{"tip_phi":0.436}]]


I'm curious as to how I "do this one more time" in order to extract the nine numbers out of the array. So that I get something like this vals =
[0.314, 0.0012, 0.436, 0.314, 0.0012, 0.436, 0.3139, 0.0012, 0.436]
that I can then turn into an array of floats.

Answer

For the ordered JSON you can try something like the following

JsonArray results = obj.getJsonArray("params");
for (int i = 0, size = results.length(); i < size; i++){
  JSONObject objectInArray = results.getJSONObject(i);
  String[] elementNames = JSONObject.getNames(objectInArray);
  for (String elementName : elementNames) {
    String value = objectInArray.getString(elementName); 
    // in value you have your double
  }
}
Comments