简体   繁体   中英

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]

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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM