改善json解析性能

时间:2018-06-15 16:34:08

标签: android json parsing

我想解析来自这个api的json数据(取自他们的示例页面):

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&outputsize=full&apikey=demo

我确实构建了一个解析方法,需要花费很长时间(在我的Galaxy A5上几秒钟)来解析数据(我知道要解析很多数据):

这就是我所做的:

private static List<PriceInfo> parsePriceDaily(JSONObject response, boolean onlyCurrentPrice) throws JSONException {
    long millis = System.currentTimeMillis();
    /* Check if this message is an Error Message = No data for symbol available.
     * If not fetch data
     * example structure
     * https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&outputsize=full&apikey=demo
     */

    /* Get the First Object - Either Meta Data or Error Message */
    Iterator<String> it = response.keys();
    String key = it.next();
    /* Is Error? */
    if (key.contains("Error Message")) {
        throw new JSONException(response.getString(key));
    }
    /* Valid Object - process metadata */
    String timeZone = response.getJSONObject(key).getString("5. Time Zone");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone(timeZone));

    /* Process datasets */
    List<PriceInfo> result = new ArrayList<>();
    key = it.next();
    JSONObject datasets = response.getJSONObject(key); /* Time Series (Daily) */
    JSONObject dataset;
    String dateString;
    for (it = datasets.keys(); it.hasNext(); ) {
        dateString = it.next(); /* dataset */
        dataset = datasets.getJSONObject(dateString);
        Date date = new Date(0); /* standard value */
        try {
            date = format.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        result.add(
                new PriceInfo(
                        date,
                        dataset.getString("1. open"),
                        dataset.getString("2. high"),
                        dataset.getString("3. low"),
                        dataset.getString("4. close"),
                        dataset.getString("5. adjusted close"),
                        dataset.getString("6. volume"),
                        dataset.getString("7. dividend amount"),
                        dataset.getString("8. split coefficient")
                )
        );
        if (onlyCurrentPrice) {
            break;
        }
    }
    Log.d(TAG, "Passed time: " + (System.currentTimeMillis() - millis));
    return result;
}

最好的改进是什么?切换到另一个JSON库?

2 个答案:

答案 0 :(得分:1)

使用Gson进行解析,使用JsonSchemaToPojo创建POJO类。

答案 1 :(得分:0)

您是否尝试过Google的gson库?