优化JSON响应的解析时间

时间:2018-08-14 06:21:29

标签: android json parsing gson

我从路线api得到一个json响应。这是我要解析的json的一部分。

"routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 18.5200884,
               "lng" : 73.9263974
            },
            "southwest" : {
               "lat" : 18.47832,
               "lng" : 73.81955219999999
            }
         },
         "copyrights" : "Map data ©2018 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "15.1 km",
                  "value" : 15078
               },
               "duration" : {
                  "text" : "42 mins",
                  "value" : 2515
               },
               "end_address" : "Swapnil Apartment, Nimbaj Nagar, Anand Nagar, Pune, Maharashtra 411051, India",
               "end_location" : {
                  "lat" : 18.480358,
                  "lng" : 73.81955219999999
               },
               "start_address" : "Magarpatta Inner Circle, Cybercity, Magarpatta City, Hadapsar, Pune, Maharashtra 411028, India",
               "start_location" : {
                  "lat" : 18.5166143,
                  "lng" : 73.925476
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "90 m",
                        "value" : 90
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 20
                     },
                     "end_location" : {
                        "lat" : 18.5167572,
                        "lng" : 73.9263146
                     },
                     "html_instructions" : "Head \u003cb\u003eeast\u003c/b\u003e on \u003cb\u003eMagarpatta Inner Circle\u003c/b\u003e toward \u003cb\u003eRoad to Trillium\u003c/b\u003e",
                     "polyline" : {
                        "points" : "yo_pBgqebMIWCWEUCUA]AQAY"
                     },
                     "start_location" : {
                        "lat" : 18.5166143,
                        "lng" : 73.925476
                     },
                     "travel_mode" : "DRIVING"
                  }

这是解析json的代码

   Gson gson = new GsonBuilder().create();
            GsonDirectionResponse directionResponse = gson.fromJson(response, GsonDirectionResponse.class);
            ArrayList<Routes> arrayListRoutes = directionResponse.getRoutes();
            if (directionResponse.getStatus().equals("OK")) {
                for (Routes route : arrayListRoutes) {
                    ArrayList<Legs> legsArrayList = route.getLegs();
                    for (Legs leg : legsArrayList) {
                        ArrayList<Steps> stepsArrayList = leg.getSteps();
                        for (Steps step : stepsArrayList) {
                            com.example.shantanub.trainingapp313.classes.directions.Location start_loc = step.getStart_Location();
                            com.example.shantanub.trainingapp313.classes.directions.Location end_loc = step.getEnd_location();

                            Log.i("start", "lat: " + start_loc.getLatitude() + "\tlng: " + start_loc.getLongitude());
                            Log.i("end", "lat: " + end_loc.getLatitude() + "\tlng: " + end_loc.getLongitude());
                        }
                    }
                }

            }

我花了很多时间来获得latitudelongitude。有没有更好的方法来解析这种响应。我需要steps数组中的纬度和经度,以便可以在地图上显示方向。我正在使用Volley库来获取响应。我没有得到如何找到解析响应所花费的确切时间,否则我将添加它以进行澄清。

1 个答案:

答案 0 :(得分:0)

要测量代码花费的时间,可以使用类似以下内容的

long startTime = System.currentTimeMillis();
someFunction();
long endTime = System.currentTimeMillis();
long timeTaken=endTime-startTime;

要解决您的问题,您可以尝试使用fastxml / jackson流式API,因为它是解析json的最快方法: https://github.com/FasterXML/jackson

在您的情况下,您可能最终会遇到这样的情况:

private int[] getCoordsJson(JsonParser jsonParser)
{
    int[] coords=new int[2];
    JsonToken jsonToken = jsonParser.nextToken();
    //iterate over all fields of an object
    while (jsonToken != JsonToken.ID_END_OBJECT) {
        if (jsonToken == JsonToken.FIELD_NAME){
            jsonToken = jsonParser.nextToken();
            if(jsonParser.getCurrentName().equals("lat")))
            {
                coords[0]=jsonParser.getIntValue();
            }else if(jsonParser.getCurrentName().equals("lng")))
            {
                coords[1]=jsonParser.getIntValue();
            }
        } 
        jsonToken = jsonParser.nextToken();
    }
    return coords;//return as simple array of ints, you can use whatever you wish
}

private void parseJson(String jsonStr)
{
    ByteArrayInputStream input = new ByteArrayInputStream(jsonStr.getBytes());

    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jsonParser = jsonFactory.createParser(input);
    JsonToken jsonToken = jsonParser.nextToken();



    int[] startCoords;
    int[] endCoords;


    while (jsonParser.hasCurrentToken()) {
        //keep iterating over tokens until we find steps array
        if (jsonToken == JsonToken.FIELD_NAME && jsonParser.getCurrentName().equals("steps")) {
            jsonToken = jsonParser.nextToken();
            //then iterate over all its fields until array ends
            while (jsonToken != JsonToken.END_ARRAY) {
                jsonToken = jsonParser.nextToken();
                if (jsonToken == JsonToken.FIELD_NAME){
                    //when we find new field - we'll check if its start_location or end_location
                    jsonToken = jsonParser.nextToken();
                    if(jsonParser.getCurrentName().equals("start_location")))
                    {
                        startCoords= getCoordsJson(jsonParser);
                    }else if(jsonParser.getCurrentName().equals("end_location")))
                    {
                        endCoords= getCoordsJson(jsonParser);
                    }

                } 
            }

        }
        jsonToken = jsonParser.nextToken();
    }
}

要使用库,请添加到build.gradle:

implementation 'com.fasterxml.jackson.core:jackson-core:2.9.6'