Home > Net >  Convert stringified array to array object in Java
Convert stringified array to array object in Java

Time:07-29

I am storing multi-dimensional arrays in text files. Using java how can I turn this stringified version of an array into an actual integer array object? I am looking for something similar to javascript's JSON.parse().

Example:

"[ [ [1,2,3], [4,5,6] ], [ [7,8,9], [10,11,12] ] ]" => 3 dimentional integer array

CodePudding user response:

What you are asking of us is "quite" a long block of code.

Instead I'll walk you down the isle for the basics of converting a stringified arr into an int array.

String input="[1, 2, 3]";
input=input.substring(1, input.length()-1); //Remove brackets...
final String[] strArr=input.split(", "); //Make a String array...
final int[] output=new int[strArr.length]; //Make a placeholder...
for(int i=0;i<strArr.length;i  ){
  output[i]=Integer.parseInt(strArr[i]);
}
System.out.println(Arrays.toString(output)); //BOOM! Stringified arr to int arr.

Now, all you have to do is to expand it into whatever array dimension you would ever like in your lifetime.

  • Related