@org.testng.annotations.Test public void testJSONEncoding() throws ParseException { String json = "{ 'str' : 'asdfasd' , 'long' : 123123123123 , 'int' : 5 , 'float' : 0.4 , 'bool' : false , 'date' : { '$date' : '2011-05-18T18:56:00Z'} , 'pat' : { '$regex' : '.*' , '$options' : ''} , 'oid' : { '$oid' : '4d83ab3ea39562db9c1ae2ae'} , 'ref' : { '$ref' : 'test.test' , '$id' : { '$oid' : '4d83ab59a39562db9c1ae2af'}} , 'code' : { '$code' : 'asdfdsa'} , 'codews' : { '$code' : 'ggggg' , '$scope' : { }} , 'ts' : { '$ts' : 1300474885 , '$inc' : 10} , 'null' : null, 'uuid' : { '$uuid' : '60f65152-6d4a-4f11-9c9b-590b575da7b5' }}"; BasicDBObject a = (BasicDBObject) JSON.parse(json); assert (a.get("str").equals("asdfasd")); assert (a.get("int").equals(5)); assert (a.get("long").equals(123123123123L)); assert (a.get("float").equals(0.4d)); assert (a.get("bool").equals(false)); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); assert (a.get("date").equals(format.parse("2011-05-18T18:56:00Z"))); Pattern pat = (Pattern) a.get("pat"); Pattern pat2 = Pattern.compile(".*", BSON.regexFlags("")); assert (pat.pattern().equals(pat2.pattern())); assert (pat.flags() == (pat2.flags())); ObjectId oid = (ObjectId) a.get("oid"); assert (oid.equals(new ObjectId("4d83ab3ea39562db9c1ae2ae"))); DBRef ref = (DBRef) a.get("ref"); assert (ref.equals(new DBRef(null, "test.test", new ObjectId("4d83ab59a39562db9c1ae2af")))); assert (a.get("code").equals(new Code("asdfdsa"))); assert (a.get("codews").equals(new CodeWScope("ggggg", new BasicBSONObject()))); assert (a.get("ts").equals(new BSONTimestamp(1300474885, 10))); assert (a.get("uuid").equals(UUID.fromString("60f65152-6d4a-4f11-9c9b-590b575da7b5"))); String json2 = JSON.serialize(a); BasicDBObject b = (BasicDBObject) JSON.parse(json2); a.equals(b); assert (a.equals(b)); }
/** * Returns the value mapped by {@code name} if it exists, coercing it if necessary. * * @throws JSONException if no such mapping exists. */ public String getString(String name) throws JSONException { Object object = get(name); String result = JSON.toString(object); if (result == null) { throw JSON.typeMismatch(name, object, "String"); } return result; }
/** * Returns the value mapped by {@code name} if it exists and is an int or can be coerced to an * int. * * @throws JSONException if the mapping doesn't exist or cannot be coerced to an int. */ public int getInt(String name) throws JSONException { Object object = get(name); Integer result = JSON.toInteger(object); if (result == null) { throw JSON.typeMismatch(name, object, "int"); } return result; }
/** * Returns the value mapped by {@code name} if it exists and is a double or can be coerced to a * double. * * @throws JSONException if the mapping doesn't exist or cannot be coerced to a double. */ public double getDouble(String name) throws JSONException { Object object = get(name); Double result = JSON.toDouble(object); if (result == null) { throw JSON.typeMismatch(name, object, "double"); } return result; }
/** * Returns the value mapped by {@code name} if it exists and is a boolean or can be coerced to a * boolean. * * @throws JSONException if the mapping doesn't exist or cannot be coerced to a boolean. */ public boolean getBoolean(String name) throws JSONException { Object object = get(name); Boolean result = JSON.toBoolean(object); if (result == null) { throw JSON.typeMismatch(name, object, "boolean"); } return result; }
/* ------------------------------------------------------------ */ public void testBigDecimal() { Object obj = JSON.parse("1.0E7"); assertTrue(obj instanceof Double); BigDecimal bd = new BigDecimal(1000.1D); String string = JSON.toString(new Object[] {bd}); obj = Array.get(JSON.parse(string), 0); assertTrue(obj instanceof Double); }
@org.testng.annotations.Test public void testObjectId() { ObjectId oid = new ObjectId(new Date()); String serialized = JSON.serialize(oid); assertEquals("{ \"$oid\" : \"" + oid + "\"}", serialized); ObjectId oid2 = (ObjectId) JSON.parse(serialized); assertEquals(oid, oid2); }
@org.testng.annotations.Test(groups = {"basic"}) public void testSerializationMethods() { // basic test of each of JSON class' serialization methods String json = "{ \"x\" : \"basic test\"}"; StringBuilder buf = new StringBuilder(); Object obj = JSON.parse(json); assertEquals(JSON.serialize(obj), json); }
@org.testng.annotations.Test public void testEscape1() { String raw = "a\nb"; DBObject x = new BasicDBObject("x", raw); assertEquals("\"a\\nb\"", JSON.serialize(raw)); assertEquals(x, JSON.parse(x.toString())); assertEquals(raw, ((DBObject) JSON.parse(x.toString())).get("x")); x = new BasicDBObject("x", "a\nb\bc\td\re"); assertEquals(x, JSON.parse(x.toString())); String thingy = "va\"lue"; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); thingy = "va\\lue"; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); assertEquals("va/lue", (String) JSON.parse("\"va\\/lue\"")); assertEquals("value", (String) JSON.parse("\"va\\lue\"")); assertEquals("va\\lue", (String) JSON.parse("\"va\\\\lue\"")); _escapeChar("\t"); _escapeChar("\b"); _escapeChar("\n"); _escapeChar("\r"); _escapeChar("\'"); _escapeChar("\""); _escapeChar("\\"); }
void _escapeChar(String s) { String thingy = "va" + s + "lue"; DBObject x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); thingy = "va" + s + s + s + "lue" + s; x = new BasicDBObject("name", thingy); x = (DBObject) JSON.parse(x.toString()); assertEquals(thingy, x.get("name")); }
@org.testng.annotations.Test public void testNumbers2() { DBObject x = new BasicDBObject("x", 123); assertEquals(x, JSON.parse(x.toString())); x = new BasicDBObject("x", 123123123123L); assertEquals(x, JSON.parse(x.toString())); x = new BasicDBObject("x", 123123123); assertEquals(x, JSON.parse(x.toString())); }
/* ------------------------------------------------------------ */ public void testParseReader() throws Exception { Map map = (Map) JSON.parse(new StringReader(test)); assertEquals(new Long(100), map.get("onehundred")); assertEquals("fred", map.get("name")); assertTrue(map.get("array").getClass().isArray()); assertTrue(map.get("w0") instanceof Woggle); assertTrue(((Woggle) map.get("w0")).nested instanceof Woggle); test = "{\"data\":{\"source\":\"15831407eqdaawf7\",\"widgetId\":\"Magnet_8\"},\"channel\":\"/magnets/moveStart\",\"connectionId\":null,\"clientId\":\"15831407eqdaawf7\"}"; map = (Map) JSON.parse(test); }
@Test public void test() { JSONCharacterSink sink = createMock(JSONCharacterSink.class); sink.append("\"foo\""); expectLastCall().once(); replay(sink); JSON json = new JSON(); json.registerJSONifier(Bean.class, new TestSinkAwareJSONifier()); json.dumpObject(sink, new Bean()); verify(sink); }
@org.testng.annotations.Test public void testDate() { Date d = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); String formattedDate = format.format(d); String serialized = JSON.serialize(d); assertEquals("{ \"$date\" : \"" + formattedDate + "\"}", serialized); Date d2 = (Date) JSON.parse(serialized); assertEquals(d.toString(), d2.toString()); assertTrue(d.equals(d2)); }
public List<Event> request_team_events(long team_number, int year) { List<Event> events = new ArrayList<>(); JsonArray attending_events_json = JSON.getAsJsonArray( HTTP.dataFromResponse( HTTP.getResponse(String.format(TEAM_EVENTS, "frc" + team_number, year)))); for (JsonElement element : attending_events_json) { Event event = JSON.getGson().fromJson(element, Event.class); events.add(event); } return events; }
@org.testng.annotations.Test public void testRegexNoOptions() { String x = "^Hello$"; String serializedPattern = "{ \"$regex\" : \"" + x + "\"}"; Pattern pattern = Pattern.compile(x); assertEquals(serializedPattern, JSON.serialize(pattern)); BasicDBObject a = new BasicDBObject("x", pattern); assertEquals("{ \"x\" : " + serializedPattern + "}", a.toString()); DBObject b = (DBObject) JSON.parse(a.toString()); assertEquals(b.get("x").getClass(), Pattern.class); assertEquals(a.toString(), b.toString()); }
/* ------------------------------------------------------------ */ @Test public void testQuote() { String test = "\"abc123|\\\"|\\\\|\\/|\\b|\\f|\\n|\\r|\\t|\\uaaaa|\""; String result = (String) JSON.parse(test, false); assertEquals("abc123|\"|\\|/|\b|\f|\n|\r|\t|\uaaaa|", result); }
/** * Serialize the given Java object into string according the given Content-Type (only JSON is * supported for now). */ public String serialize(Object obj, String contentType) throws ApiException { if (contentType.startsWith("application/json")) { return json.serialize(obj); } else { throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); } }
@org.testng.annotations.Test(groups = {"basic"}) public void testString() { assertEquals(JSON.serialize(JSON.parse("{'csdf' : \"foo\"}")), "{ \"csdf\" : \"foo\"}"); assertEquals(JSON.serialize(JSON.parse("{'csdf' : \'foo\'}")), "{ \"csdf\" : \"foo\"}"); assertEquals(JSON.serialize(JSON.parse("{'csdf' : \"a\\\"b\"}")), "{ \"csdf\" : \"a\\\"b\"}"); assertEquals( JSON.serialize(JSON.parse("{\n\t\"id\":\"1689c12eb234c54a84ebd100\",\n}")), "{ \"id\" : \"1689c12eb234c54a84ebd100\"}"); }
/** * Returns the value mapped by {@code name} if it exists and is a {@code JSONObject}. * * @throws JSONException if the mapping doesn't exist or is not a {@code JSONObject}. */ public JSONObject getJSONObject(String name) throws JSONException { Object object = get(name); if (object instanceof JSONObject) { return (JSONObject) object; } else { throw JSON.typeMismatch(name, object, "JSONObject"); } }
@org.testng.annotations.Test(groups = {"basic"}) public void testLongValues() { Long bigVal = Integer.MAX_VALUE + 1L; String test = String.format("{ \"x\" : %d}", bigVal); assertEquals(JSON.serialize(JSON.parse(test)), test); Long smallVal = Integer.MIN_VALUE - 1L; String test2 = String.format("{ \"x\" : %d}", smallVal); assertEquals(JSON.serialize(JSON.parse(test2)), test2); try { JSON.parse("{\"ReallyBigNumber\": 10000000000000000000 }"); fail("JSONParseException should have been thrown"); } catch (JSONParseException e) { // fall through } }
@Test public void build() { Map<String, Object> data = new HashMap<>(); data.put("id", 1); data.put("name", "John"); String j = JSON.build(data); assertEquals("{\"id\": 1, \"name\": \"John\"}", j); }
/* ------------------------------------------------------------ */ public void testParse() { Map map = (Map) JSON.parse(test); assertEquals(new Long(100), map.get("onehundred")); assertEquals("fred", map.get("name")); assertEquals(new Double(-0.2), map.get("small")); assertTrue(map.get("array").getClass().isArray()); assertTrue(map.get("w0") instanceof Woggle); assertTrue(((Woggle) map.get("w0")).nested instanceof Woggle); assertEquals(-101, ((Woggle) ((Woggle) map.get("w0")).nested).number); assertTrue(map.containsKey("NaN")); assertEquals(null, map.get("NaN")); assertTrue(map.containsKey("undefined")); assertEquals(null, map.get("undefined")); test = "{\"data\":{\"source\":\"15831407eqdaawf7\",\"widgetId\":\"Magnet_8\"},\"channel\":\"/magnets/moveStart\",\"connectionId\":null,\"clientId\":\"15831407eqdaawf7\"}"; map = (Map) JSON.parse(test); }
/* ------------------------------------------------------------ */ public void testStripComment() { String test = "\n\n\n\t\t " + "// ignore this ,a [ \" \n" + "/* " + "{ " + "\"onehundred\" : 100 ," + "\"name\" : \"fred\" ," + "\"empty\" : {} ," + "\"map\" : {\"a\":-1.0e2} ," + "\"array\" : [\"a\",-1.0e2,[],null,true,false] ," + "} */"; Object o = JSON.parse(test, false); assertTrue(o == null); o = JSON.parse(test, true); assertTrue(o instanceof Map); assertEquals("fred", ((Map) o).get("name")); }
@org.testng.annotations.Test(groups = {"basic"}) public void testBasic() { assertEquals(JSON.serialize(JSON.parse("{}")), "{ }"); assertEquals(JSON.parse(""), null); assertEquals(JSON.parse(" "), null); assertEquals(JSON.parse(null), null); boolean threw = false; try { JSON.parse("{"); } catch (JSONParseException e) { threw = true; } assertEquals(threw, true); threw = false; try { JSON.parse("}"); } catch (JSONParseException e) { threw = true; } assertEquals(threw, true); threw = false; try { JSON.parse("{{}"); } catch (JSONParseException e) { threw = true; } assertEquals(threw, true); threw = false; try { JSON.parse("4"); } catch (JSONParseException e) { threw = true; } assertEquals(threw, false); threw = false; assertEquals(4, JSON.parse("4")); }
@Override public ArrayList<RemoteObject> deserializeArray(String queryScope, String input) { String bodyFormat = getDeserializationBodyFormat(); if (XML.equals(bodyFormat)) { return deserializeArrayAsXml(queryScope, input); } else if (JSON.equals(bodyFormat)) { return deserializeArrayAsJson(queryScope, input); } else { return deserializeArrayAsJson(queryScope, input); } }
@org.testng.annotations.Test(groups = {"basic"}) public void testArray() { assertEquals(JSON.serialize(JSON.parse("{'csdf' : [\"foo\"]}")), "{ \"csdf\" : [ \"foo\"]}"); assertEquals( JSON.serialize(JSON.parse("{'csdf' : [3, 5, \'foo\', null]}")), "{ \"csdf\" : [ 3 , 5 , \"foo\" , null ]}"); assertEquals( JSON.serialize(JSON.parse("{'csdf' : [3.0, 5.0, \'foo\', null]}")), "{ \"csdf\" : [ 3.0 , 5.0 , \"foo\" , null ]}"); assertEquals( JSON.serialize(JSON.parse("{'csdf' : [[],[[]],false]}")), "{ \"csdf\" : [ [ ] , [ [ ]] , false]}"); }
/** * Creates a new {@code JSONObject} with name/value mappings from the next object in the tokener. * * @param readFrom a tokener whose nextValue() method will yield a {@code JSONObject}. * @throws JSONException if the parse fails or doesn't yield a {@code JSONObject}. */ public JSONObject(JSONTokener readFrom) throws JSONException { /* * Getting the parser to populate this could get tricky. Instead, just * parse to temporary JSONObject and then steal the data from that. */ Object object = readFrom.nextValue(); if (object instanceof JSONObject) { this.nameValuePairs = ((JSONObject) object).nameValuePairs; } else { throw JSON.typeMismatch(object, "JSONObject"); } }
/** * Maps {@code name} to {@code value}, clobbering any existing name/value mapping with the same * name. If the value is {@code null}, any existing mapping for {@code name} is removed. * * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, Double, * {@link #NULL}, or {@code null}. May not be {@link Double#isNaN() NaNs} or {@link * Double#isInfinite() infinities}. * @return this object. */ public JSONObject put(String name, Object value) throws JSONException { if (value == null) { nameValuePairs.remove(name); return this; } if (value instanceof Number) { // deviate from the original by checking all Numbers, not just floats & doubles JSON.checkDouble(((Number) value).doubleValue()); } nameValuePairs.put(checkName(name), value); return this; }
@Test public void content_type_is_overwritten_when_defined_in_specification() { // Given MockMvcRequestSpecification specToMerge = new MockMvcRequestSpecBuilder().setContentType(JSON).build(); // When MockMvcRequestSpecification spec = given().contentType(XML).spec(specToMerge); // Then assertThat(implOf(spec).getRequestContentType()).isEqualTo(JSON.toString()); }