Java Code Examples for org.json.JSONTokener#nextValue()

The following examples show how to use org.json.JSONTokener#nextValue() . 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: PreUtils.java    From Hook with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: StringsContentProvider.java    From coursera-android with MIT License 6 votes vote down vote up
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();
            }
        }
    }
}
 
Example 3
Source File: deserializejson.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
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 );
	}
}
 
Example 4
Source File: TreeJsonActionTest.java    From javasimon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 5
Source File: JSONTokenerTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }

}
 
Example 6
Source File: GraphResponse.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source File: TableJsonActionTest.java    From javasimon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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());
}
 
Example 8
Source File: Blog.java    From Cotable with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source File: Response.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
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 10
Source File: Response.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
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 11
Source File: Response.java    From platform-friends-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 12
Source File: Response.java    From HypFacebook with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 13
Source File: Response.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 5 votes vote down vote up
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 14
Source File: JsonData.java    From cube-sdk with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: MyPushMessageReceiver.java    From styT with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example 16
Source File: ListJsonActionTest.java    From javasimon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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());
}
 
Example 17
Source File: Response.java    From Klyph with MIT License 5 votes vote down vote up
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 18
Source File: BlogDetail.java    From Cotable with Apache License 2.0 4 votes vote down vote up
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;

}
 
Example 19
Source File: JSONUtils.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
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 '}'");
        }
    }
}
 
Example 20
Source File: BaiduTranslate.java    From ArscEditor with Apache License 2.0 4 votes vote down vote up
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();
	}