Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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]

share|improve this question
    
new JSONArray(array) is sufficient to supply a (primitive) array to the constructor. – user2864740 Aug 12 '14 at 7:48
up vote 1 down vote accepted

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]
share|improve this answer
    
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 Aug 12 '14 at 7:37
    
@Apoorv no need I can just directly add a modifier on it. – Rod_Algonquin Aug 12 '14 at 7:39
    
Yes you can do it either way. – Apoorv Aug 12 '14 at 7:39
    
About autoboxing stackoverflow.com/questions/1073919/… – fisher3421 Aug 12 '14 at 8:09

Try this..

You need to convert long into Long then you can use that in JSONArray

    long [] array = new long[]{1, 2, 3};
    List<Long> longArray = asList(array);

    JSONArray jsonArray = new JSONArray(longArray);
    jsonArray.toString();

asList() method

public static List<Long> asList(final long[] l) {
    return new AbstractList<Long>() {
        public Long get(int i) {return l[i];}
        // throws NPE if val == null
        public Long set(int i, Long val) {
            Long oldVal = l[i];
            l[i] = val;
            return oldVal;
        }
        public int size() { return l.length;}
    };
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.