ryanmattscott ryanmattscott - 1 year ago 77
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 = {
{"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
and the valArray is

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download