【问题标题】:Java- How to store Parsing nested json data into Java listJava-如何将解析嵌套的json数据存储到Java列表中
【发布时间】:2021-01-29 15:45:03
【问题描述】:

我想在 google api 的帮助下每天监控我的网站性能

我尝试从 pagespeedonline 的 googleapi 获取网络请求中的 items

但它不适用于我的代码

REST API 链接:

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

我试着变得特别

lighthouseResult -> audits -> network-requests ->details-> items

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

我试过下面的代码


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");
    
      }
   }

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

提前致谢

【问题讨论】:

  • 不是您的问题的答案,但希望是您实际问题的答案(监控站点性能) 如果您想监控日常活动,PSI API 对您没有那么有用。您可能想查看this answer I gave,了解如何衡量应用程序的性能并构建您自己的解决方案,因为它将为您提供更好的真实世界数据,因为现场数据的 PSI 数据是 28 天滚动的,而实验室数据不会波动除非你改变东西

标签: java json google-api pagespeed-insights google-pagespeed-insights-api


【解决方案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)

由此我们可以识别出带有 inline 变量的 missed-format 变量,同时将其标记为 JSON 字符串

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

【讨论】:

    【解决方案2】:

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

    代码 sn-p

    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>
    

    【讨论】:

      【解决方案3】:

      假设您在inline 变量中有完整的json 响应,您可以将其转换为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()));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 2018-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多