2

我试图在谷歌 api 的帮助下监控我的网站性能日常活动

我试图从 pagespeedonline 的 googleapi 获取网络请求中的项目

但它不适用于我的代码

REST API 链接:

https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://lifemachi.blogspot.com&key=AIzaSyBfHVlhNEnf26Ea8-ZOhiYOe0HrQZtLvRI&category=performance&strategy=desktop

我试着变得特别

lighthouseResult -> 审计 -> 网络请求 -> 详细信息-> 项目

并将每个项目存储到记录中...

我试过下面的代码


package FirstTestNgPackage;



import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import org.json.*;

public class testingJSON {
       static String inline = "";
   public static void main(String args[]) throws JSONException, InterruptedException, IOException {
       // url
       URL url = new URL("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://lifemachi.blogspot.com&key=AIzaSyBfHVlhNEnf26Ea8-ZOhiYOe0HrQZtLvRI&category=performance&strategy=desktop");
      // read it from URL
       Scanner sc = new Scanner(url.openStream()); Thread.sleep(300);
       String jsonDataString = sc.nextLine();
       while(sc.hasNext())
        {
            inline+=sc.nextLine();
        }
       sc.close();
        
      List<String> list = new ArrayList<String>();
      
   
// just print that inline var
        
        System.out.println(inline);
        System.out.println("--------1");
    
      }
   }

我得到了正确的输出......但是如何将项目值存储在列表中?

提前致谢

4

3 回答 3

1

如果您只想items在整个 JSON 响应中检索 JSON 数组,可以使用JsonPath以下方法轻松完成:

代码片段

List<String> items = JsonPath.parse(inline).read("$.lighthouseResult.audits.network-requests.details.items");

Maven依赖

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
于 2020-10-16T00:45:45.500 回答
1

首先,您必须将名为“inline”的输出数组解析为有效的 JSON 字符串。在这里您可以使用org.json库的功能,

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import org.json.*;

    public class testingJSON {

        static String inline = "";

        public static void main(String args[]) throws JSONException, InterruptedException, IOException {
     
         // url
         URL url = new URL("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://lifemachi.blogspot.com&key=AIzaSyBfHVlhNEnf26Ea8-ZOhiYOe0HrQZtLvRI&category=performance&strategy=desktop");
    
        // read it from URL

        Scanner sc = new Scanner(url.openStream()); Thread.sleep(300);
        String jsonDataString = sc.nextLine();

            while(sc.hasNext()){
                inline+=sc.nextLine();
            }

            sc.close();

            // just print that inline var
            System.out.println(inline);
            System.out.println("--------1");

            //Tokenize the string data json array
            JSONArray data = new JSONArray(new JSONObject(new JSONTokener(inline)));

            //or JSONArray data = new JSONArray(new JSONObject(inline));

            //The array list we want to insert the formatted JSON string
            ArrayList<String> list = new ArrayList<String>();
    
            if(data !=null){
                for(int i=0;i<data.length();i++){
                    list.add(data.getString(i));
                }
            }

            System.out.println(list);
        }
    }

在这里我有以下错误

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 4 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
    at org.json.JSONObject.<init>(JSONObject.java:184)
    at testingJson.main(testingJson.java:31)

由此我们可以识别出带有内联变量的丢失格式,同时将其标记为 JSON 字符串

在 JSON 字符串中,格式必须是这样的 [{ JSON 数据}]

于 2020-10-15T10:55:09.400 回答
0

假设您在变量中有完整的 json 响应inline,您可以将其转换为JSONObject然后继续读取子属性。

JSONObject jsonObject = new JSONObject(inline);
JSONObject lighthouseResult = jsonObject.getJSONObject("lighthouseResult");
JSONObject audits = lighthouseResult.getJSONObject("audits");
JSONObject networkRequests = audits.getJSONObject("network-requests");
JSONObject details = networkRequests.getJSONObject("details");

//Notice that here we are reading an array
JSONArray items = details.getJSONArray("items");

// Create String list and add elements to it from items JSONArray object
List<String> itemsList = new ArrayList<>();
items.forEach(item -> itemsList.add(item.toString()));
于 2020-10-15T11:07:50.347 回答