繁体   English   中英

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

[英]Java- How to store Parsing nested json data into Java list

我试图在 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

我特别想得到

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

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

提前致谢

首先,您必须将名为“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)

从中我们可以识别出带有内联变量的遗漏格式,同时将其标记为 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()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM