Home > Net >  Convert JSONArray of double value to a 2 dimensional double array
Convert JSONArray of double value to a 2 dimensional double array

Time:05-30

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}
};

CodePudding user response:

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;
  }
}

CodePudding user response:

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);
  }
}

CodePudding user response:

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

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