Java原始数组JSONArray [英] java primitive array to JSONArray

查看:143
本文介绍了Java原始数组JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换成Java原始数组JSONArray,但我有如下奇怪behaviour.My code。

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();

输出 [[J @ 532372dc]

为什么我得到这个输出?我想这样的输出 [1,2,3]

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

推荐答案

问题:

Arrays.asList(array)

您不能变换原始类型到类别阵列,它必须是对象类型的阵列。由于 asList 需要一个 T ... 请注意,它需要一个对象。

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.

为什么它的工作?

这是因为在传递给它的参数,它会 autoBox ,因为它是数组类型的对象。

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

解决方案:

您需要将其更改为它的包装类,并把它作为一个数组。

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

示例:

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

结果:

[1, 2, 3]

这篇关于Java原始数组JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆