KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

Convert JSONArray of double value to a 2 dimensional double array

Let's say I have some JSONArray values like below

JSONArray arr1 = new JSONArray ();
arr1.put(46.974004);
arr1.put(-86.33614);
JSONArray arr2 = new JSONArray ();
arr2.put(39.135086);
arr2.put(26.363614);
JSONArray allArray = new JSONArray ();
allArray.put(arr1);
allArray.put(arr2);

Which is the shortest way to convert allArray to a 2 dimensional double array so the output will be the same as this

double[][] doubles = new double[]{
    new double[]{46.974004, -86.33614},
    new double[]{39.135086, 26.363614}
};

Upvotes: 0

Views: 490

Answers (4)

Eugene
Eugene

Reputation: 6005

Using streams:

double[][] array = IntStream.range(0, allArray.length()).
                             mapToObj(allArray::getJSONArray).
                             map(jsonArray-> IntStream.range(0, jsonArray.length()).mapToDouble(jsonArray::getDouble).toArray()).
                             toArray(double[][]::new);

Upvotes: 0

Benoit Cuvelier
Benoit Cuvelier

Reputation: 776

You can consider using Jackson objectMapper if you can for a more elegant solution :

 double[][] result = objectMapper.readValue(allArray.toString(), double[][].class);

Upvotes: 0

Zamir
Zamir

Reputation: 441

I assume that your json array has a fixed size therefore I have defined the array size with the length of arr.

double[][] d = new double[arr.length()][];

for (int i = 0; i < arr.length(); i++) {
  d[i] = new double[arr.getJSONArray(i).length()];
  for (int j = 0; j < arr.getJSONArray(i).length(); j++) {
    d[i][j] = arr.getJSONArray(i).getDouble(j);
  }
}

Upvotes: 0

idanz
idanz

Reputation: 877

If you assume that all 'sub-arrays' are from the same length, you can do a basic iteration as follows:

double[][] newAllArray = new double[allArray.length()][allArray.getJSONArray(0).length()];
for (int i = 0; i < allArray.length(); i++) {
  for (int j = 0; j < allArray.getJSONArray(i).length(); j++) {
    double originalValue = allArray.getJSONArray(i).getDouble(j);
    newAllArray[i][j] = originalValue;
  }
}

Upvotes: 1

Related Questions