Java-如何将嵌套的json数据解析到Java列表中

问题描述

我想借助Google Api每天监控我的网站性能

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

但不适用于我的代码

REST API链接

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

我想变得特别

灯塔结果->审核->网络请求->详细信息->项目

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

我尝试了以下代码


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

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

预先感谢

解决方法

首先,您必须将名为“ inline”的输出错误解析为有效的JSON string。 在这里,您可以使用 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 变量的 缺少格式 的东西,同时将其标记为JSON字符串

在JSON字符串中,格式必须为 [{JSON数据}]

,

如果您只想在整个JSON响应中检索JSON数组items,则可以使用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>
,

假设您在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()));