3

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]

1
  • new JSONArray(array) is sufficient to supply a (primitive) array to the constructor. Commented Aug 12, 2014 at 7:48

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

5 Comments

You will need to cast the values of array to long or else it will give Type mismatch: cannot convert from int to Long
@Apoorv no need I can just directly add a modifier on it.
Yes you can do it either way.
How we can do reverse.? like i have have String[] and i want to convert it to json format like {'0','1','2'}.
0

If what you want is just to convert a primitive integer array to a JSONArray, cut the long story short.

JSONArray jsonArray = new JSONArray(Arrays.asList(longArray).get(0));

* You will need a try/catch block

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.