I'm trying to put two int [] and a double [] in JSON format to send through my java servlet. This is what I have so far.
private JSONObject doStuff(double[] val, int[] col_idx, int[] row_ptr){
String a = JSONValue.toJSONString(val);
String b = JSONValue.toJSONString(col_idx);
String c = JSONValue.toJSONString(row_ptr);
JSONObject jo = new JSONObject();
jo.put("val",a)
jo.put("col",b);
jo.put("row",c);
return jo;
}
But when I print the JSONobject, I get this unreadable result:
{"val":"[D@62ce3190","col":"[I@4f18179d","row":"[I@36b66cfc"}
I get the same result in javascript where I am sending the JSONObject to. Is there a problem with the conversion from numbers to string? Should I perhaps use JSONArray instead?
Answered in 2022Using JSON. stringify() , we convert the JavaScript array to Json string. And using JSON. parse() , we convert Json string to a Json object.
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
It is because the toString
method of int[]
or double[]
is returning the Object's default Object.toString()
.
Replace with Arrays.toString(int[]/double[])
, you will get expected result.
Check this answer for more explantion about toString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With