下面列出了org.json.JSONTokener#nextValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Map<Integer, String> getMap(String key) {
Map<Integer, String> mage2nameMap = new HashMap<>();
String age2name = sp.getString(key, null);
if (age2name.length() > 0) {
JSONTokener jsonTokener = new JSONTokener(age2name);
try {
JSONArray jsonArray = (JSONArray) jsonTokener.nextValue();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
mage2nameMap.put(jsonObject.getInt("age"), jsonObject.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mage2nameMap;
}
static List<GraphResponse> createResponsesFromString(
String responseString,
HttpURLConnection connection,
GraphRequestBatch requests
) throws FacebookException, JSONException, IOException {
JSONTokener tokener = new JSONTokener(responseString);
Object resultObject = tokener.nextValue();
List<GraphResponse> responses = createResponsesFromObject(
connection,
requests,
resultObject);
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;
}
/**
* Verifies that JSONTokener can read a stream that contains a value. After
* the reading is done, check that the stream is left in the correct state
* by reading the characters after. All valid cases should reach end of stream.
* @param testStr
* @return
* @throws Exception
*/
private Object nextValue(String testStr) throws JSONException {
try(StringReader sr = new StringReader(testStr);){
JSONTokener tokener = new JSONTokener(sr);
Object result = tokener.nextValue();
if( result == null ) {
throw new JSONException("Unable to find value token in JSON stream: ("+tokener+"): "+testStr);
}
char c = tokener.nextClean();
if( 0 != c ) {
throw new JSONException("Unexpected character found at end of JSON stream: "+c+ " ("+tokener+"): "+testStr);
}
return result;
}
}
@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 static cfData getCfDataFromJSon(String jsonString, boolean strictMapping) throws Exception {
if ( jsonString.isEmpty() )
return cfStringData.EMPTY_STRING;
else if (jsonString.startsWith("{"))
return convertToCf(new JSONObject(jsonString), strictMapping);
else if (jsonString.startsWith("["))
return convertToCf(new JSONArray(jsonString), strictMapping);
else{
JSONTokener tokener = new JSONTokener( jsonString );
Object value = tokener.nextValue();
if ( tokener.next() > 0 ){
throw new Exception("invalid JSON string");
}
if ( value instanceof String ){
return new cfStringData( (String) value );
}else if ( value instanceof Boolean ){
return cfBooleanData.getcfBooleanData( (Boolean) value, ( (Boolean) value ).booleanValue() ? "true" : "false" );
}else if ( value instanceof Number ){
return cfNumberData.getNumber( (Number) value );
}else if ( value == JSONObject.NULL ){
return cfNullData.NULL;
}else
return new cfStringData( jsonString );
}
}
private void readDb() {
@SuppressWarnings("ConstantConditions")
SharedPreferences sharedPref = getContext().getSharedPreferences(DB_FILE_NAME, Context.MODE_PRIVATE);
if (null == sharedPref) return;
String dbString = sharedPref.getString("DBString", null);
if (null != dbString) {
db.clear();
JSONTokener parser = new JSONTokener(dbString);
while (parser.more()) {
try {
JSONObject tmp = (JSONObject) parser.nextValue();
Iterator<String> iterator = tmp.keys();
while (iterator.hasNext()) {
String value = iterator.next();
int id = tmp.getInt(value);
db.put(id, new DataRecord(id, value));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
@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());
}
}
@Test
public void testExecute() throws Exception {
TestActionContext context = new TestActionContext("/data/table.json");
TableJsonAction action = new TableJsonAction(context);
action.readParameters();
action.execute();
assertEquals(context.getContentType(), "application/json");
String json = context.toString();
assertTrue(json.contains("{\"name\":\"A\",\"type\":\"STOPWATCH\",\"counter\":3,\"total\":600,\"min\":100,\"mean\":200,\"last\":300,\"max\":300,\"standardDeviation\":100"));
assertTrue(json.contains("{\"name\":\"B\",\"type\":\"STOPWATCH\",\"counter\":2,\"total\":300,\"min\":100,\"mean\":150,\"last\":100,\"max\":200,\"standardDeviation\":71"));
assertTrue(json.contains("{\"name\":\"C\",\"type\":\"STOPWATCH\",\"counter\":1,\"total\":300,\"min\":300,\"mean\":300,\"last\":300,\"max\":300,\"standardDeviation\":0"));
assertTrue(json.contains("{\"name\":\"X\",\"type\":\"COUNTER\",\"counter\":2,\"total\":\"\",\"min\":1,\"mean\":\"\",\"last\":\"\",\"max\":4"));
// 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 JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length(); i++) {
object = jsonArray.get(i);
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
String name = jsonObject.getString("name");
names.remove(name);
}
}
}
assertTrue(names.isEmpty());
}
/**
* 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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
public static JsonData create(String str) {
Object object = null;
if (str != null && str.length() >= 0) {
try {
JSONTokener jsonTokener = new JSONTokener(str);
object = jsonTokener.nextValue();
} catch (Exception e) {
}
}
return create(object);
}
@Test
public void testExecute() throws Exception {
TestActionContext context = new TestActionContext("/data/table.json");
ListJsonAction action = new ListJsonAction(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 JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length(); i++) {
object = jsonArray.get(i);
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
String name = jsonObject.getString("name");
names.remove(name);
}
}
}
assertTrue(names.isEmpty());
}
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;
}
public void doTranslate() throws IOException, JSONException {
// 格式化需要翻译的内容为UTF-8编码
String str_utf = URLEncoder.encode(str, "UTF-8");
// 百度翻译api
String str_url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=GOr7jiTs5hiQvkHqDNg4KSTV&q="
+ str_utf + "&from=" + fromString + "&to=" + toString;
// 将api网址转化成URL
URL url_word = new URL(str_url);
// 连接到该URL
URLConnection connection = (URLConnection) url_word.openConnection();
// 获取输入流
InputStream is = connection.getInputStream();
// 转化成读取流
InputStreamReader isr = new InputStreamReader(is);
// 转化成缓冲读取流
BufferedReader br = new BufferedReader(isr);
// 每行的内容
String line;
// 字符串处理类
StringBuilder sBuilder = new StringBuilder();
// 读取每行内容
while ((line = br.readLine()) != null) {
// 在字符串末尾追加内容
sBuilder.append(line);
}
/**
* 单词解析
*/
JSONTokener jtk = new JSONTokener(sBuilder.toString());
JSONObject jObject = (JSONObject) jtk.nextValue();
JSONArray jArray = jObject.getJSONArray("trans_result");
Log.i("TAG", url_word.toString());
Log.i("TAG", jObject.toString());
JSONObject sub_jObject_1 = jArray.getJSONObject(0);
// dst对应的内容就是翻译结果
result = sub_jObject_1.getString("dst");
br.close();
isr.close();
is.close();
}
public static Map<String, Object> parseJSON(String jsonBody) throws JSONException {
final Map<String, Object> params = new HashMap<String, Object>();
final JSONTokener x = new JSONTokener(jsonBody);
char c;
String key;
if (x.nextClean() != '{') {
throw new IllegalArgumentException(format("String '%s' is not a valid JSON object representation, a JSON object text must begin with '{'",
jsonBody));
}
for (;;) {
c = x.nextClean();
switch (c) {
case 0:
throw new IllegalArgumentException(format("String '%s' is not a valid JSON object representation, a JSON object text must end with '}'",
jsonBody));
case '}':
return params;
default:
x.back();
key = x.nextValue().toString();
}
/*
* The key is followed by ':'. We will also tolerate '=' or '=>'.
*/
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw new IllegalArgumentException(format("String '%s' is not a valid JSON object representation, expected a ':' after the key '%s'",
jsonBody, key));
}
Object value = x.nextValue();
// guard from null values
if (value != null) {
if (value instanceof JSONArray) { // only plain simple arrays in this version
JSONArray array = (JSONArray) value;
Object[] values = new Object[array.length()];
for (int i = 0; i < array.length(); i++) {
values[i] = array.get(i);
}
value = values;
}
params.put(key, value);
}
/*
* Pairs are separated by ','. We will also tolerate ';'.
*/
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return params;
}
x.back();
break;
case '}':
return params;
default:
throw new IllegalArgumentException("Expected a ',' or '}'");
}
}
}
public static BlogDetail parse(String data) {
BlogDetail blog = new BlogDetail("", "<p>Hello, I'm Lemuel.</p>");
if (data != null && !data.equals("")) {
try {
JSONTokener jsonParser = new JSONTokener(data);
JSONObject content = (JSONObject) jsonParser.nextValue();
blog.setBody(content.getString("data"));
} catch (Exception e) {
e.printStackTrace();
}
}
return blog;
}