Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int arrays to json object in java

Tags:

java

json

arrays

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?

like image 593
kongshem Avatar asked Oct 29 '15 12:10

kongshem


People also ask

How do I convert an array to JSON?

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.

Can JSON objects have arrays?

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.

How do you write an array of objects in JSON?

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.

How do you add a JSON object to an array in Java?

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.


1 Answers

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.

like image 80
rajuGT Avatar answered Oct 01 '22 13:10

rajuGT