Skip to content

Instantly share code, notes, and snippets.

@shiffman
Created November 5, 2011 03:20
Show Gist options
  • Save shiffman/1341056 to your computer and use it in GitHub Desktop.
Save shiffman/1341056 to your computer and use it in GitHub Desktop.
Java Objects to JSON Arrays
java.awt.Rectangle r = new java.awt.Rectangle(50,60,100,150);
JSONArray ja1 = new JSONArray();
ja1.put(r);
System.out.println(ja1.toString());
// ["java.awt.Rectangle[x=50,y=60,width=100,height=150]"]
float[] stuff = {1.0f,2.0f,3.0f,5.0f};
JSONArray ja2 = new JSONArray();
ja2.put(stuff);
System.out.println(ja2.toString());
// [[1,2,3,5]]
ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
for (int i = 0; i < 3; i++) {
rects.add(new Rectangle(i,i*2,i*3,i*4));
}
JSONArray ja3 = new JSONArray();
ja3.put(rects);
System.out.println(ja3.toString());
// [["java.awt.Rectangle[x=0,y=0,width=0,height=0]","java.awt.Rectangle[x=1,y=2,width=3,height=4]","java.awt.Rectangle[x=2,y=4,width=6,height=8]"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment