5

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?

kongshem
  • 322
  • 1
  • 5
  • 23
  • If you try printing `val` on the console, it will print the same thing. It is the address of `val` array and similarly for the others. – user007 Oct 29 '15 at 12:33
  • Indeed. `String a = Arrays.toString(val)` did the trick though. – kongshem Oct 29 '15 at 12:37
  • You need to first convert your arrays into readable format(convert it into list using Arrays.asList()), and then process it. – Vivek Singh Oct 29 '15 at 12:38

2 Answers2

7

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.

Community
  • 1
  • 1
rajuGT
  • 6,224
  • 2
  • 26
  • 44
  • 1
    I figured it out riiight before your answer, but thanks. Will mark this as the correct answer after the "you can accept an answer in 3 minutes" prompt. – kongshem Oct 29 '15 at 12:44
0

Instead of using

jo.put("val",a)
jo.put("col",b);
jo.put("row",c);

Use;

jo.put("val",val);
jo.put("col",col_idx);
jo.put("row",row_ptr);
Shivam
  • 649
  • 2
  • 8
  • 20