【问题标题】:Optimize parsing time for json response优化 json 响应的解析时间
【发布时间】:2018-08-14 06:21:29
【问题描述】:

我有一个来自方向 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 库来获取响应。我没有得到如何找到解析响应所需的确切时间,否则我会添加它以进行澄清。

【问题讨论】:

    标签: android json parsing gson


    【解决方案1】:

    要衡量你的代码所花费的时间,你可以使用类似的东西:

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

    为了解决您的问题,您可以尝试使用 fasterxml/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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 2015-02-04
      • 2015-05-15
      • 1970-01-01
      • 2013-10-17
      • 2013-03-27
      相关资源
      最近更新 更多