Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java primitive array to JSONArray

I'm trying convert java primitive array to JSONArray, but I have strange behaviour.My code below.

long [] array = new long[]{1, 2, 3};
JSONArray jsonArray = new JSONArray(Arrays.asList(array));
jsonArray.toString();

output is ["[J@532372dc"]

Why Do I get this output? I want to get output like this [1, 2, 3]

like image 258
vmtrue Avatar asked Apr 25 '26 23:04

vmtrue


1 Answers

problem:

Arrays.asList(array)

You cant transform an array of primitive types to Collections that it needs to be an array of Objects type. Since asList expects a T... note that it needs to be an object.

why is it working?

That is because upon passing it in the parameter it will autoBox it since array are type object.

solution:

You need to change it to its wrapper class, and use it as an array.

sample:

Long[] array = new Long[]{1L, 2L, 3L};
JSONArray jsonArray = new JSONArray(Arrays.asList(array));
jsonArray.toString();

result:

[1, 2, 3]
like image 92
Rod_Algonquin Avatar answered Apr 28 '26 11:04

Rod_Algonquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!