下面列出了怎么用org.json.JSONTokener的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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);
}
}
@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();
}
}
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");
}
}
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;
}
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;
}
@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"));
}
@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);
}
}
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());
}
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();
}
/**
* 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;
}
}
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;
}
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);
}
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);
}
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());
}
@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());
}
public void testTokenerConstructorNull() throws JSONException {
try {
new JSONObject((JSONTokener) null);
fail();
} catch (NullPointerException e) {
}
}
/**
* Some applications rely on parsing '#' to lead an end-of-line comment.
* http://b/2571423
*/
public void testNextCleanHashComments() throws JSONException {
JSONTokener tokener = new JSONTokener("A # B */ /* C */ \nD #");
assertEquals('A', tokener.nextClean());
assertEquals('D', tokener.nextClean());
assertEquals('\0', tokener.nextClean());
}
private static Object decodeViaJSONObject(String json) throws JSONException {
JSONTokener tokener = new JSONTokener(json);
Object value = tokener.nextValue();
if (value instanceof JSONArray) {
return decodeArray((JSONArray) value);
} else if (value instanceof JSONObject) {
return decodeObject((JSONObject) value);
} else {
throw new IllegalArgumentException("No top level object or array: " + json);
}
}
/**
* Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long,
* Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()}
*
* @param responseBody response bytes to be assembled in String and parsed as JSON
* @return Object parsedResponse
* @throws org.json.JSONException exception if thrown while parsing JSON
*/
protected Object parseResponse(byte[] responseBody) throws JSONException {
if (null == responseBody)
return null;
Object result = null;
//trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If JSON is not valid this will return null
String jsonString = getResponseString(responseBody, getCharset());
if (jsonString != null) {
jsonString = jsonString.trim();
if (useRFC5179CompatibilityMode) {
if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
result = new JSONTokener(jsonString).nextValue();
}
} else {
// Check if the string is an JSONObject style {} or JSONArray style []
// If not we consider this as a string
if ((jsonString.startsWith("{") && jsonString.endsWith("}"))
|| jsonString.startsWith("[") && jsonString.endsWith("]")) {
result = new JSONTokener(jsonString).nextValue();
}
// Check if this is a String "my String value" and remove quote
// Other value type (numerical, boolean) should be without quote
else if (jsonString.startsWith("\"") && jsonString.endsWith("\"")) {
result = jsonString.substring(1, jsonString.length() - 1);
}
}
}
if (result == null) {
result = jsonString;
}
return result;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
// Log.e(TAG, "===bmob push reciever===" + intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING));
String msg = intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING);
//ToastUtil.show(context, msg, Toast.LENGTH_SHORT);
JSONTokener jsonTokener = new JSONTokener(msg);
String message = null;
try {
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
message = jsonObject.getString("alert");
} catch (JSONException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
PendingIntent it = PendingIntent.getActivity(context, 0, new Intent(context, ws_Main3Activity.class), 0);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
notification.setContentTitle("通知")
.setContentText(message)
.setLargeIcon(bitmap)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(it)
.setAutoCancel(true);
manager.notify(1, notification.build());
}
}
private void validateMessage(Schema schema, Object message) {
final String stringMessage;
try {
stringMessage = OBJECT_MAPPER.writeValueAsString(message);
} catch (Exception e) {
throw new RuntimeException("While converting to string", e);
}
schema.validate(new JSONObject(new JSONTokener(stringMessage)));
}
private void loadSchema(String key) {
File schemaFile = new File(schemaBase, key);
try (InputStream schemaStream = new FileInputStream(schemaFile)) {
JSONObject rawSchema = new JSONObject(new JSONTokener(schemaStream));
schemas.put(key, SchemaLoader.load(rawSchema, new Loader()));
} catch (Exception e) {
throw new RuntimeException("While loading schema " + schemaFile.getAbsolutePath(), e);
}
}
public void validateEnvelope(String registryId, String siteName) {
try {
UdmiSchema.Envelope envelope = new UdmiSchema.Envelope();
envelope.deviceId = deviceId;
envelope.deviceRegistryId = registryId;
// Don't use actual project id because it should be abstracted away.
envelope.projectId = fakeProjectId();
envelope.deviceNumId = makeNumId(envelope);
String envelopeJson = OBJECT_MAPPER.writeValueAsString(envelope);
schemas.get(ENVELOPE_JSON).validate(new JSONObject(new JSONTokener(envelopeJson)));
} catch (Exception e) {
throw new IllegalStateException("Validating envelope " + deviceId, e);
}
checkConsistency(siteName);
}
public void testNextToDoesntStopOnNull() {
String message = "nextTo() shouldn't stop after \\0 characters";
JSONTokener tokener = new JSONTokener(" \0\t \fABC \n DEF");
assertEquals(message, "ABC", tokener.nextTo("D"));
assertEquals(message, '\n', tokener.next());
assertEquals(message, "", tokener.nextTo("D"));
}
public void testParsingNoObjects() {
try {
new JSONTokener("").nextValue();
fail();
} catch (JSONException e) {
}
}
/**
* json 解析器,反序列化
*
* @param jsonStr
* @param type
* @param <T>
* @return
* @throws Exception
*/
public static <T> T parseJson(String jsonStr, Class<T> type) throws Exception {
if (jsonStr == null || jsonStr.equals("")) {
throw new NullPointerException("JsonString can't be null");
}
T data = type.getDeclaredConstructor().newInstance();
Field[] fields = type.getDeclaredFields();
JSONObject jsonObject = (JSONObject) new JSONTokener(jsonStr).nextValue();
for (Field field : fields) {
field.setAccessible(true);
field.set(data, jsonObjectToObject(jsonObject, field));
}
return data;
}
/**
* Parse the dato to Blog List.
*
* @param data the data contains the blog infos.
* @return the Blog List
*/
public static List<Blog> parse(String data) {
List<Blog> blogList = null;
Blog blog = null;
if (data != null && !data.equals("")) try {
JSONTokener jsonParser = new JSONTokener(data);
JSONObject content = (JSONObject) jsonParser.nextValue();
JSONArray list = content.getJSONArray("data");
if (list.length() > 0) blogList = new ArrayList<>();
for (int i = 0; i < list.length(); ++i) {
JSONObject info = (JSONObject) list.get(i);
blog = new Blog();
blog.setAuthor_name(info.getString("author"));
blog.setPostId(info.getString("blog_id"));
blog.setUrl(StringUtils.toUrl(info.getString("blog_url")));
blog.setBlogId(StringUtils.toInt(info.getString("blog_id")));
blog.setBlogapp(info.getString("blogapp"));
blog.setComments(StringUtils.toInt(info.getString("comment")));
blog.setSummary(info.getString("content"));
blog.setReads(StringUtils.toInt(info.getString("hit")));
blog.setTitle(info.getString("title"));
blog.setUpdated(StringUtils.toDate(info.getString("public_time")));
if (blogList != null) {
blogList.add(blog);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return blogList;
}
public void testJsonSelectedFields() throws Exception
{
JSONObject jsonPostData = createItemJSON(this.referencingDocNodeRef);
JSONArray jsonFields = new JSONArray();
jsonFields.put("cm:name");
jsonFields.put("cm:title");
jsonFields.put("cm:publisher");
jsonPostData.put("fields", jsonFields);
// Submit the JSON request.
String jsonPostString = jsonPostData.toString();
Response rsp = sendRequest(new PostRequest(FORM_DEF_URL, jsonPostString,
APPLICATION_JSON), 200);
String jsonResponseString = rsp.getContentAsString();
JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
assertNotNull(jsonParsedObject);
JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
JSONArray fieldsArray = (JSONArray)definitionObject.get("fields");
assertEquals("Expected 2 fields", 2, fieldsArray.length());
// get the name and title definitions
JSONObject nameField = (JSONObject)fieldsArray.get(0);
JSONObject titleField = (JSONObject)fieldsArray.get(1);
String nameFieldDataKey = nameField.getString("dataKeyName");
String titleFieldDataKey = titleField.getString("dataKeyName");
// get the data and check it
JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
assertNotNull("Expected to find cm:name data", formDataObject.get(nameFieldDataKey));
assertNotNull("Expected to find cm:title data", formDataObject.get(titleFieldDataKey));
assertEquals(TEST_FORM_TITLE, formDataObject.get("prop_cm_title"));
}
public static String getServiceAccountProjectId(String credentialsPath) {
String project = null;
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;
}