我期待找到这个问题,但我不能。也许我正在搜索错误的东西。
我有一个原始整数数组(int[]
),我希望将其转换为{J}可解析的String
,转换回相同的{{1} }。
我试过这段代码:
int[]
当我打印// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
变量时,它的值为:jSONString
然而,我期望一个合适的JSON字符串,如:["[I@40558d08"]
不确定引号,但你明白了。
我想跟踪本地图像(在drawable文件夹中),所以我将它们的id存储在int数组中,然后我想以JSON String的形式存储这个数组,稍后将由另一个解析活动。我知道我可以通过Intent附加功能实现这一目标。但我必须使用SharedPreferences。
感谢您的帮助!
答案 0 :(得分:6)
您不必使用Arrays.asList实例化JSONArray。它可以采用普通的原始数组。
尝试JSONArray mJSONArray = new JSONArray(image_ids_primitive);
如果你使用的API级别低于19,那么一个简单的方法就是遍历int数组并放置它们。
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
答案 1 :(得分:2)
试试这种方式
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
答案 2 :(得分:2)
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
答案 3 :(得分:2)
如果你想要一个JSON数组而不一定是一个对象,你可以使用JSONArray
。
或者,快速破解:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
打印出来
[1, 2, 3, 4, 5, 6, 7]
这是有效的JSON。如果你想要比这更复杂的东西,显然JSONObject
是你的朋友。
答案 4 :(得分:1)
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
答案 5 :(得分:0)
此代码将实现您的目标...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
这将为您提供{“3”:“203”,“2”:“200”,“1”:“100”,“4”:“4578”}作为字符串。
不完全确定为什么它的顺序不正确,但按键排序非常容易。