org.json.JSONTokener Java Examples
The following examples show how to use
org.json.JSONTokener.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpellCheckDecisionManagerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
public JSONObject createJsonSearchRequest(String searchTerm) throws JSONException { String requestStr = "{" + "\"queryConsistency\" : \"DEFAULT\"," + "\"textAttributes\" : []," + "\"allAttributes\" : []," + "\"templates\" : [{" + "\"template\" : \"%(cm:name cm:title cm:description ia:whatEvent ia:descriptionEvent lnk:title lnk:description TEXT TAG)\"," + "\"name\" : \"keywords\"" + "}" + "]," + "\"authorities\" : [\"GROUP_EVERYONE\", \"ROLE_ADMINISTRATOR\", \"ROLE_AUTHENTICATED\", \"admin\"]," + "\"tenants\" : [\"\"]," + "\"query\" : \"(" + searchTerm + " AND (+TYPE:\\\"cm:content\\\" OR +TYPE:\\\"cm:folder\\\")) AND -TYPE:\\\"cm:thumbnail\\\" AND -TYPE:\\\"cm:failedThumbnail\\\" AND -TYPE:\\\"cm:rating\\\" AND -TYPE:\\\"st:site\\\" AND -ASPECT:\\\"st:siteContainer\\\" AND -ASPECT:\\\"sys:hidden\\\" AND -cm:creator:system AND -QNAME:comment\\\\-*\"," + "\"locales\" : [\"en\"]," + "\"defaultNamespace\" : \"http://www.alfresco.org/model/content/1.0\"," + "\"defaultFTSFieldOperator\" : \"AND\"," + "\"defaultFTSOperator\" : \"AND\"" + "}"; InputStream is = new ByteArrayInputStream(requestStr.getBytes()); Reader reader = new BufferedReader(new InputStreamReader(is)); JSONObject json = new JSONObject(new JSONTokener(reader)); return json; }
Example #2
Source File: AndroidJsonHandlerTest.java From KeenClient-Java with MIT License | 6 votes |
@Test public void readSimpleMap() throws Exception { JSONObject mockJsonObject = mock(JSONObject.class); List<String> keys = Arrays.asList("result"); when(mockJsonObject.keys()).thenReturn(keys.iterator()); when(mockJsonObject.get("result")).thenReturn("dummyResult"); JSONTokener mockJsonTokener = mock(JSONTokener.class); when(mockJsonTokener.nextValue()).thenReturn(mockJsonObject); when(mockJsonObjectManager.newTokener(anyString())).thenReturn(mockJsonTokener); // This string doesn't matter, but it's what we mimic with the mocks. String mapResponse = "{\"result\": \"dummyResult\"}"; StringReader reader = new StringReader(mapResponse); Map<String, Object> map = handler.readJson(reader); assertNotNull(map); assertEquals(1, map.size()); assertTrue(map.containsKey("result")); assertEquals("dummyResult", map.get("result")); }
Example #3
Source File: Message.java From AndroidFrame with Apache License 2.0 | 6 votes |
public String toJson() { JSONObject jsonObject= new JSONObject(); try { jsonObject.put(CALLBACK_ID_STR, getCallbackId()); jsonObject.put(DATA_STR, getData()); jsonObject.put(HANDLER_NAME_STR, getHandlerName()); String data = getResponseData(); if (TextUtils.isEmpty(data)) { jsonObject.put(RESPONSE_DATA_STR, data); } else { jsonObject.put(RESPONSE_DATA_STR, new JSONTokener(data).nextValue()); } jsonObject.put(RESPONSE_DATA_STR, getResponseData()); jsonObject.put(RESPONSE_ID_STR, getResponseId()); return jsonObject.toString(); } catch (JSONException e) { e.printStackTrace(); } return null; }
Example #4
Source File: JSONTokenerTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testCharacterNavigation() throws JSONException { JSONTokener abcdeTokener = new JSONTokener("ABCDE"); assertEquals('A', abcdeTokener.next()); assertEquals('B', abcdeTokener.next('B')); assertEquals("CD", abcdeTokener.next(2)); try { abcdeTokener.next(2); fail(); } catch (JSONException e) { } assertEquals('E', abcdeTokener.nextClean()); assertEquals('\0', abcdeTokener.next()); assertFalse(abcdeTokener.more()); abcdeTokener.back(); assertTrue(abcdeTokener.more()); assertEquals('E', abcdeTokener.next()); }
Example #5
Source File: JMXQueryHelper.java From eagle with Apache License 2.0 | 6 votes |
private static Map<String, JMXBean> parseStream(InputStream is) { final Map<String, JMXBean> resultMap = new HashMap<String, JMXBean>(); final JSONTokener tokener = new JSONTokener(is); final JSONObject jsonBeansObject = new JSONObject(tokener); final JSONArray jsonArray = jsonBeansObject.getJSONArray("beans"); int size = jsonArray.length(); for (int i = 0; i < size; ++i) { final JSONObject obj = (JSONObject) jsonArray.get(i); final JMXBean bean = new JMXBean(); final Map<String, Object> map = new HashMap<String, Object>(); bean.setPropertyMap(map); final JSONArray names = obj.names(); int jsonSize = names.length(); for (int j = 0; j < jsonSize; ++j) { final String key = names.getString(j); Object value = obj.get(key); map.put(key, value); } final String nameString = (String) map.get("name"); resultMap.put(nameString, bean); } return resultMap; }
Example #6
Source File: FeedbackServlet.java From recaptcha-codelab with Apache License 2.0 | 6 votes |
private JSONObject postAndParseJSON(URL url, String postData) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty( "charset", StandardCharsets.UTF_8.displayName()); urlConnection.setRequestProperty( "Content-Length", Integer.toString(postData.length())); urlConnection.setUseCaches(false); urlConnection.getOutputStream() .write(postData.getBytes(StandardCharsets.UTF_8)); JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream()); return new JSONObject(jsonTokener); }
Example #7
Source File: FeedbackServlet.java From recaptcha-codelab with Apache License 2.0 | 6 votes |
private JSONObject postAndParseJSON(URL url, String postData) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty( "charset", StandardCharsets.UTF_8.displayName()); urlConnection.setRequestProperty( "Content-Length", Integer.toString(postData.length())); urlConnection.setUseCaches(false); urlConnection.getOutputStream() .write(postData.getBytes(StandardCharsets.UTF_8)); JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream()); return new JSONObject(jsonTokener); }
Example #8
Source File: JsonAsyncTask.java From YouTube-In-Background with MIT License | 6 votes |
/** * Checks if JSON data is correctly formatted * * @param string the raw JSON response * @return int */ private int checkJsonError(String string) { try { Object json = new JSONTokener(string).nextValue(); if (json instanceof JSONObject) { return JSON_OBJECT; } else if (json instanceof JSONArray) { return JSON_ARRAY; } else { return JSON_ERROR; } } catch (JSONException e) { e.printStackTrace(); return JSON_ERROR; } }
Example #9
Source File: CapabilitySchemaValidator.java From AppiumTestDistribution with GNU General Public License v3.0 | 6 votes |
public void validateCapabilitySchema(JSONObject capability) { try { isPlatformInEnv(); InputStream inputStream = getClass().getResourceAsStream(getPlatform()); JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream)); Schema schema = SchemaLoader.load(rawSchema); schema.validate(new JSONObject(capability.toString())); validateRemoteHosts(); } catch (ValidationException e) { if (e.getCausingExceptions().size() > 1) { e.getCausingExceptions().stream() .map(ValidationException::getMessage) .forEach(System.out::println); } else { LOGGER.info(e.getErrorMessage()); } throw new ValidationException("Capability json provided is missing the above schema"); } }
Example #10
Source File: JsonParser.java From analysis-model with MIT License | 6 votes |
@Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (Reader reader = readerFactory.create()) { JSONObject jsonReport = (JSONObject) new JSONTokener(reader).nextValue(); Report report = new Report(); if (jsonReport.has(ISSUES)) { JSONArray issues = jsonReport.getJSONArray(ISSUES); StreamSupport.stream(issues.spliterator(), false) .filter(o -> o instanceof JSONObject) .map(o -> convertToIssue((JSONObject) o)) .filter(Optional::isPresent) .map(Optional::get) .forEach(report::add); } return report; } catch (IOException | JSONException e) { throw new ParsingException(e); } }
Example #11
Source File: JSONTokenerTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testBackNextAndMore() throws JSONException { JSONTokener abcTokener = new JSONTokener("ABC"); assertTrue(abcTokener.more()); abcTokener.next(); abcTokener.next(); assertTrue(abcTokener.more()); abcTokener.next(); assertFalse(abcTokener.more()); abcTokener.back(); assertTrue(abcTokener.more()); abcTokener.next(); assertFalse(abcTokener.more()); abcTokener.back(); abcTokener.back(); abcTokener.back(); abcTokener.back(); // you can back up before the beginning of a String! assertEquals('A', abcTokener.next()); }
Example #12
Source File: RelativeURITest.java From json-schema with Apache License 2.0 | 6 votes |
@Test public void test() throws Exception { System.out.println(JettyWrapper.class .getResource("/org/everit/json/schema/relative-uri/").toExternalForm()); JettyWrapper jetty = new JettyWrapper("/org/everit/json/schema/relative-uri"); jetty.start(); try { SchemaLoader.builder() .resolutionScope("http://localhost:1234/schema/") .schemaJson( new JSONObject(new JSONTokener(IOUtils.toString(getClass().getResourceAsStream( "/org/everit/json/schema/relative-uri/schema/main.json"))))) .build().load().build(); } finally { jetty.stop(); } }
Example #13
Source File: AudioJsonParser.java From AssistantBySDK with Apache License 2.0 | 6 votes |
public static String parseIatResult(String json) { if(json.startsWith("<"))return AudioXmlParser.parseXmlResult(json,0); StringBuffer ret = new StringBuffer(); try { JSONTokener tokener = new JSONTokener(json); JSONObject joResult = new JSONObject(tokener); JSONArray words = joResult.getJSONArray("ws"); for (int i = 0; i < words.length(); i++) { // 转写结果词,默认使用第一个结�? JSONArray items = words.getJSONObject(i).getJSONArray("cw"); JSONObject obj = items.getJSONObject(0); ret.append(obj.getString("w")); // 如果�?��多�?选结果,解析数组其他字段 // for(int j = 0; j < items.length(); j++) // { // JSONObject obj = items.getJSONObject(j); // ret.append(obj.getString("w")); // } } } catch (Exception e) { e.printStackTrace(); } return ret.toString(); }
Example #14
Source File: TreeJsonActionTest.java From javasimon with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testExecute() throws Exception { TestActionContext context = new TestActionContext("/data/tree.json"); TreeJsonAction action = new TreeJsonAction(context); action.readParameters(); action.execute(); assertEquals(context.getContentType(), "application/json"); String json = context.toString(); // Test JSON format with an external library JSONTokener jsonTokener = new JSONTokener(json); Set<String> names = new HashSet<>(); names.add("A"); names.add("B"); names.add("C"); Object object = jsonTokener.nextValue(); if (object instanceof JSONObject) { visitJSONObject((JSONObject) object, names); } assertTrue(names.isEmpty()); }
Example #15
Source File: ToopherAPI.java From oxAuth with MIT License | 6 votes |
@Override public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); // TODO: check entity == null String json = EntityUtils.toString(entity); try { return (JSONObject) new JSONTokener(json).nextValue(); } catch (JSONException e) { throw new ClientProtocolException("Could not interpret response as JSON", e); } }
Example #16
Source File: HentaiCafeParser.java From Hentoid with Apache License 2.0 | 6 votes |
private static JSONArray getJSONArrayFromString(String s) { @SuppressWarnings("RegExpRedundantEscape") Pattern pattern = Pattern.compile(".*\\[\\{ *(.*) *\\}\\].*"); Matcher matcher = pattern.matcher(s); Timber.d("Match found? %s", matcher.find()); if (matcher.groupCount() > 0) { String results = matcher.group(1); results = "[{" + results + "}]"; try { return (JSONArray) new JSONTokener(results).nextValue(); } catch (JSONException e) { Timber.e(e, "Couldn't build JSONArray from the provided string"); } } return null; }
Example #17
Source File: AbstractSolrQueryHTTPClient.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException { PostMethod post = new PostMethod(url); if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) { post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8"); post.setRequestEntity(requestEntity); try { httpClient.executeMethod(post); if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); post.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(post); } } if (post.getStatusCode() != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString()); } Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler JSONObject json = new JSONObject(new JSONTokener(reader)); return json; } finally { post.releaseConnection(); } }
Example #18
Source File: JSONtoFmModel.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Convert JSON Array string to Freemarker-compatible data model * * @param jsonString String * @return model * @throws JSONException */ public static Map<String, Object> convertJSONArrayToMap(String jsonString) throws JSONException { Map<String, Object> model = new HashMap<String, Object>(); JSONArray ja = new JSONArray(new JSONTokener(jsonString)); model.put(ROOT_ARRAY, convertJSONArrayToList(ja)); return model; }
Example #19
Source File: JsonBasedPropertiesProvider.java From cfg4j with Apache License 2.0 | 5 votes |
/** * Get {@link Properties} for a given {@code inputStream} treating it as a JSON file. * * @param inputStream input stream representing JSON file * @return properties representing values from {@code inputStream} * @throws IllegalStateException when unable to read properties */ @Override public Properties getProperties(InputStream inputStream) { requireNonNull(inputStream); Properties properties = new Properties(); try { JSONTokener tokener = new JSONTokener(inputStream); if (tokener.end()) { return properties; } if (tokener.nextClean() == '"') { tokener.back(); properties.put("content", tokener.nextValue().toString()); } else { tokener.back(); JSONObject obj = new JSONObject(tokener); Map<String, Object> yamlAsMap = convertToMap(obj); properties.putAll(flatten(yamlAsMap)); } return properties; } catch (Exception e) { throw new IllegalStateException("Unable to load json configuration from provided stream", e); } }
Example #20
Source File: RestClient.java From nbp with Apache License 2.0 | 5 votes |
@Override public Object parseResponseBody(String body) throws JSONException { Object json = new JSONTokener(body).nextValue(); if(json instanceof JSONArray) return new JSONArray(body); return new JSONObject(body); }
Example #21
Source File: RunningActionsPost.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected Action identifyAction(WebScriptRequest req, Status status, Cache cache) { // Which action did they ask for? String nodeRef = req.getParameter("nodeRef"); if(nodeRef == null) { try { JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent())); if(! json.has("nodeRef")) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not find required 'nodeRef' parameter"); } nodeRef = json.getString("nodeRef"); } catch (IOException iox) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from request.", iox); } catch (JSONException je) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from request.", je); } } // Does it exist in the repo? NodeRef actionNodeRef = new NodeRef(nodeRef); if(! nodeService.exists(actionNodeRef)) { return null; } // Load the specified action Action action = runtimeActionService.createAction(actionNodeRef); return action; }
Example #22
Source File: OrderbookTest.java From bitfinex-v2-wss-api-java with Apache License 2.0 | 5 votes |
/** * Test the build from JSON array */ @Test public void createOrderbookConfigurationFromJSON() { final String message = "{\"event\":\"subscribed\",\"channel\":\"book\",\"chanId\":3829,\"symbol\":\"tBTCUSD\",\"prec\":\"P0\",\"freq\":\"F0\",\"len\":\"25\",\"pair\":\"BTCUSD\"}"; final JSONTokener tokener = new JSONTokener(message); final JSONObject jsonObject = new JSONObject(tokener); final BitfinexOrderBookSymbol configuration = BitfinexOrderBookSymbol.fromJSON(jsonObject); Assert.assertEquals(BitfinexCurrencyPair.of("BTC","USD"), configuration.getCurrencyPair()); Assert.assertEquals(BitfinexOrderBookSymbol.Frequency.F0, configuration.getFrequency()); Assert.assertEquals(BitfinexOrderBookSymbol.Precision.P0, configuration.getPrecision()); Assert.assertEquals(25, (int) configuration.getPricePoints()); }
Example #23
Source File: GcpOptions.java From flo with Apache License 2.0 | 5 votes |
/** * {@link ServiceOptions#getServiceAccountProjectId()} reimplemented here to avoid breaking if users use a version * of google-api-client that does not have {@link GoogleCredential#getServiceAccountProjectId()}. */ private static String getServiceAccountProjectId() { String project = null; String credentialsPath = System.getenv(CREDENTIAL_ENV_NAME); if (credentialsPath != null) { try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); project = json.getString("project_id"); } catch (IOException | JSONException ex) { // ignore } } return project; }
Example #24
Source File: AbstractSolrAdminHTTPClient.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Executes an action or a command in SOLR using REST API * * @param httpClient HTTP Client to be used for the invocation * @param url Complete URL of SOLR REST API Endpoint * @return A JSON Object including SOLR response * @throws UnsupportedEncodingException */ protected JSONObject getOperation(HttpClient httpClient, String url) throws UnsupportedEncodingException { GetMethod get = new GetMethod(url); try { httpClient.executeMethod(get); if(get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = get.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); get.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(get); } } if (get.getStatusCode() != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException("Request failed " + get.getStatusCode() + " " + url.toString()); } Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet())); JSONObject json = new JSONObject(new JSONTokener(reader)); return json; } catch (IOException | JSONException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { get.releaseConnection(); } }
Example #25
Source File: Response.java From platform-friends-android with BSD 2-Clause "Simplified" License | 5 votes |
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException { JSONTokener tokener = new JSONTokener(responseString); Object resultObject = tokener.nextValue(); List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache); Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), responseString.length(), responses); return responses; }
Example #26
Source File: Response.java From FacebookImageShareIntent with MIT License | 5 votes |
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException { JSONTokener tokener = new JSONTokener(responseString); Object resultObject = tokener.nextValue(); List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache); Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), responseString.length(), responses); return responses; }
Example #27
Source File: IOUtil.java From droidddle with Apache License 2.0 | 5 votes |
public static JSONObject readJsonObject(String json) throws IOException, JSONException { JSONTokener tokener = new JSONTokener(json); Object val = tokener.nextValue(); if (!(val instanceof JSONObject)) { throw new JSONException("Expected JSON object."); } return (JSONObject) val; }
Example #28
Source File: Response.java From Abelana-Android with Apache License 2.0 | 5 votes |
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException { JSONTokener tokener = new JSONTokener(responseString); Object resultObject = tokener.nextValue(); List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache); Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), responseString.length(), responses); return responses; }
Example #29
Source File: DotsData.java From commcare-android with Apache License 2.0 | 5 votes |
public static DotsDay deserialize(String day) { try { return deserialize(new JSONArray(new JSONTokener(day))); } catch (JSONException e) { throw new RuntimeException(e); } }
Example #30
Source File: ClientConnection.java From yacy_grid_mcp with GNU Lesser General Public License v2.1 | 5 votes |
public static String loadFromEtherpad(String etherpadUrlstub, String etherpadApikey, String padID) throws IOException { String padurl = etherpadUrlstub + "/api/1/getText?apikey=" + etherpadApikey + "&padID=" + padID; InputStream is = new URL(padurl).openStream(); JSONTokener serviceResponse = new JSONTokener(is); JSONObject json = new JSONObject(serviceResponse); String text = json.getJSONObject("data").getString("text"); return text; }