JDS
JDS

Reputation: 16998

Java JSON serialization of an integer array?

This should be simple.

I have an integer array that I want to encode in JSON formatting so I can pass it to a web service:

int[] myInts = new int[length-1];
myInts = {5, 6, 7, 1, 12, ..., 78}; 

JSONArray jArray = new JSONArray();
//now what? 

Thanks.

Upvotes: 0

Views: 4241

Answers (2)

Daniel Figueroa
Daniel Figueroa

Reputation: 10676

If i where you I'd create a JSONObject first and then create the JSONArray and use

myJsonArray.put(value);

and finally add the jsonarray to the JSONObject. I suppose this would work nice for a small set of numbers however if you want to pass a large set of integers there should be a more elegant way to do it than this.

Upvotes: 1

Sahil Muthoo
Sahil Muthoo

Reputation: 12506

int[] myInts = {1,2,3,4,5}; 
JSONArray jArray = new JSONArray(myInts);
System.out.println(jArray.toString());

Upvotes: 0

Related Questions