ThomasBracher/JSON — pull request #1 by kapr (2013-05-19 15:50:41+00:00)
Title: Generic get method

Something I missed having in the original JSON-java library. This cleans up the client code by not having to cast returning objects or use one of the specific getXXXX methods. The method only uses a basic cast, as do the other getXXXX methods and will still throw a ClassCastException if one is thrown.

I also changed to casts to use the boxed object types as they are nullable. Java's auto-boxing will take care of the rest.

Here is a Junit test case:

```java
import static org.junit.Assert.assertEquals;

import java.util.List;

import org.bracher.json.JSONArray;
import org.bracher.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

public class JSONObjectGenericTest {

private final JSONObject object = new JSONObject();

@Before
public void setUp() {
object.put("testBool", true);
object.put("testString", "String value");
object.put("testDouble", 1.00);
object.put("testInt", 500);
object.put("testLong", 8000L);
object.put("testFloat", 5.5F);
}

@Test
public void testPrimitives() {
assertEquals(true, object.get("testBool", Boolean.class));
assertEquals("String value", object.get("testString", String.class));
assertEquals(new Double(1.00), object.get("testDouble", Double.class));
assertEquals(new Integer(500), object.get("testInt", Integer.class));
assertEquals(new Long(8000L), object.get("testLong", Long.class));
assertEquals(new Float(5.5F), object.get("testFloat", Float.class));
}

@Test
public void testJsonObjects() {
final JSONObject jobj = new JSONObject().put("someKey", "someValue");
object.put("jobj", jobj);

final JSONObject jobj2 = object.get("jobj", JSONObject.class);
assertEquals(jobj2, jobj);
}

@Test
public void testJsonArray() {
final JSONArray jarr = new JSONArray().pushInt(500).pushBoolean(true);
object.put("jarr", jarr);

final JSONArray jarr2 = object.get("jarr", JSONArray.class);
assertEquals(jarr2, jarr);

assertEquals(new Integer(500), jarr.get(0, Integer.class));
assertEquals(true, jarr.get(1, Boolean.class));
}

@Test(expected=IllegalArgumentException.class)
public void testUnauthorizedClass() {
// List is not an authorized class
object.get("testList", List.class);
}

@Test(expected=ClassCastException.class)
public void testWrongType() {
// The integer is not a boolean
object.get("testInt", Boolean.class);
}
}
```