【发布时间】:2016-03-30 15:41:06
【问题描述】:
我有一个 JSON 文件 airports.json,其中包含 5720 个对象,我想将 Java 中的文件解析为 Objects Airport。
下面的代码是我如何解析它的,问题是,完全解析所有文件需要花费太多时间,大约 1 分 50 秒。
ArrayList<Airport> arrayAirports = new ArrayList<>();
String json_response = loadJSONFromAsset();
try {
JSONObject airports = new JSONObject(json_response.trim());
Log.d("Length Array 0", String.valueOf(airports.names().length()));
Log.d("Length Array 1", String.valueOf(arrayAirports.size()));
for(int i = 0; i<airports.names().length(); i++){
JSONObject jsonAirport = airports.getJSONObject(airports.names().getString(i));
Airport newAirport = new Airport();
newAirport.name = jsonAirport.getString("name");
newAirport.city = jsonAirport.getString("city");
newAirport.country = jsonAirport.getString("country");
newAirport.latitude = jsonAirport.getString("latitude");
newAirport.longitude = jsonAirport.getString("longitude");
newAirport.altitude = jsonAirport.getString("altitude");
newAirport.iata = jsonAirport.getString("iata");
newAirport.icao = jsonAirport.getString("icao");
newAirport.timeZone = jsonAirport.getString("timezone");
newAirport.dst = jsonAirport.getString("dst");
arrayAirports.add(newAirport);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.d("Length Array 2", String.valueOf(arrayAirports.size()));
有没有办法更快地解析它。 顺便说一句,我的朋友正在使用 Objective C 来解析它。
【问题讨论】:
-
尝试使用第三方库而不是手动操作github.com/google/gson
-
我现在正在尝试使用它,但我不知道如何循环遍历 JSON 文件并每次添加一个 Airport 对象
-
JSONObject.names() 在每次迭代中...两次?
-
这是我能想到的唯一方法