/** * 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; }
/* ------------------------------------------------------------ */ 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); }
@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()); }
/** * Returns an array with the values corresponding to {@code names}. The array contains null for * names that aren't mapped. This method returns null if {@code names} is either null or empty. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { JSONArray result = new JSONArray(); if (names == null) { return null; } int length = names.length(); if (length == 0) { return null; } for (int i = 0; i < length; i++) { String name = JSON.toString(names.opt(i)); result.put(opt(name)); } return result; }
/** * Process HTTP request. * * @param act Action. * @param req Http request. * @param res Http response. */ private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) { res.setContentType("application/json"); res.setCharacterEncoding("UTF-8"); GridRestCommand cmd = command(req); if (cmd == null) { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (!authChecker.apply(req.getHeader("X-Signature"))) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } GridRestResponse cmdRes; Map<String, Object> params = parameters(req); try { GridRestRequest cmdReq = createRequest(cmd, params, req); if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq); cmdRes = hnd.handle(cmdReq); if (cmdRes == null) throw new IllegalStateException("Received null result from handler: " + hnd); byte[] sesTok = cmdRes.sessionTokenBytes(); if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok)); res.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { res.setStatus(HttpServletResponse.SC_OK); U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e); cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage()); } catch (Throwable e) { U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e); throw e; } JsonConfig cfg = new GridJettyJsonConfig(); // Workaround for not needed transformation of string into JSON object. if (cmdRes.getResponse() instanceof String) cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC); if (cmdRes.getResponse() instanceof GridClientTaskResultBean && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String) cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC); JSON json; try { json = JSONSerializer.toJSON(cmdRes, cfg); } catch (JSONException e) { U.error(log, "Failed to convert response to JSON: " + cmdRes, e); json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg); } try { if (log.isDebugEnabled()) log.debug("Parsed command response into JSON object: " + json.toString(2)); res.getWriter().write(json.toString()); if (log.isDebugEnabled()) log.debug( "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']'); } catch (IOException e) { U.error(log, "Failed to send HTTP response: " + json.toString(2), e); } }
@Test public void testToString() { HashMap map = new HashMap(); HashMap obj6 = new HashMap(); HashMap obj7 = new HashMap(); Woggle w0 = new Woggle(); Woggle w1 = new Woggle(); w0.name = "woggle0"; w0.nested = w1; w0.number = 100; w1.name = "woggle1"; w1.nested = null; w1.number = -101; map.put("n1", null); map.put("n2", new Integer(2)); map.put("n3", new Double(-0.00000000003)); map.put("n4", "4\n\r\t\"4"); map.put( "n5", new Object[] { "a", new Character('b'), new Integer(3), new String[] {}, null, Boolean.TRUE, Boolean.FALSE }); map.put("n6", obj6); map.put("n7", obj7); map.put("n8", new int[] {1, 2, 3, 4}); map.put("n9", new JSON.Literal("[{}, [], {}]")); map.put("w0", w0); obj7.put("x", "value"); String s = JSON.toString(map); assertTrue(s.indexOf("\"n1\":null") >= 0); assertTrue(s.indexOf("\"n2\":2") >= 0); assertTrue(s.indexOf("\"n3\":-3.0E-11") >= 0); assertTrue(s.indexOf("\"n4\":\"4\\n") >= 0); assertTrue(s.indexOf("\"n5\":[\"a\",\"b\",") >= 0); assertTrue(s.indexOf("\"n6\":{}") >= 0); assertTrue(s.indexOf("\"n7\":{\"x\":\"value\"}") >= 0); assertTrue(s.indexOf("\"n8\":[1,2,3,4]") >= 0); assertTrue(s.indexOf("\"n9\":[{}, [], {}]") >= 0); assertTrue( s.indexOf( "\"w0\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle0\",\"nested\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle1\",\"nested\":null,\"number\":-101},\"number\":100}") >= 0); Gadget gadget = new Gadget(); gadget.setShields(42); gadget.setWoggles(new Woggle[] {w0, w1}); s = JSON.toString(new Gadget[] {gadget}); assertTrue(s.startsWith("[")); assertTrue(s.indexOf("\"modulated\":false") >= 0); assertTrue(s.indexOf("\"shields\":42") >= 0); assertTrue(s.indexOf("\"name\":\"woggle0\"") >= 0); assertTrue(s.indexOf("\"name\":\"woggle1\"") >= 0); }
/* ------------------------------------------------------------ */ @Test public void testZeroByte() { String withzero = "\u0000"; JSON.toString(withzero); }
/** * Returns the value mapped by {@code name} if it exists, coercing it if necessary. Returns {@code * fallback} if no such mapping exists. */ public String optString(String name, String fallback) { Object object = opt(name); String result = JSON.toString(object); return result != null ? result : fallback; }