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

huangapple go评论83阅读模式
英文:

Java- How to store Parsing nested json data into Java list

问题

package FirstTestNgPackage;

import java.io.IOException;
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=YOUR_API_KEY&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");
    }
}

Note: Please replace "YOUR_API_KEY" in the URL with your actual Google API key. The code you provided seems to fetch data from the Google Pagespeed Insights API and store it in the inline variable. If you want to extract and store the items values from the JSON response, you would need to parse the JSON and navigate to the desired structure using the JSONObject and JSONArray classes provided by the org.json library. Unfortunately, the provided code doesn't show the complete parsing logic to achieve this.

英文:

I Tring to monitor my site performance day by day activity with help of google api

and i tried to fetch items in network request from googleapi of pagespeedonline

but its not working on my code

REST API link :

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

and i try to get particularly

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

and store each items into record...

i tried below codes


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 = &quot;&quot;;
   public static void main(String args[]) throws JSONException, InterruptedException, IOException {
	   // url
	   URL url = new URL(&quot;https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://lifemachi.blogspot.com&amp;key=AIzaSyBfHVlhNEnf26Ea8-ZOhiYOe0HrQZtLvRI&amp;category=performance&amp;strategy=desktop&quot;);
	  // 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&lt;String&gt; list = new ArrayList&lt;String&gt;();
      
   
// just print that inline var
		
		System.out.println(inline);
		System.out.println(&quot;--------1&quot;);
    
      }
   }

and i got proper output...
but how to store items values in list ?

Thanks in advance

答案1

得分: 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&amp;key=YourAPIKeyHere&amp;category=performance&amp;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 数据 } ]

英文:

First you must parse the output arrray named "inline" to valid JSON string .
Here you can use the functionalities of org.json library,

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import org.json.*;
public class testingJSON {
static String inline = &quot;&quot;;
public static void main(String args[]) throws JSONException, InterruptedException, IOException {
// url
URL url = new URL(&quot;https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://lifemachi.blogspot.com&amp;key=AIzaSyBfHVlhNEnf26Ea8-ZOhiYOe0HrQZtLvRI&amp;category=performance&amp;strategy=desktop&quot;);
// 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(&quot;--------1&quot;);
//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&lt;String&gt; list = new ArrayList&lt;String&gt;();
if(data !=null){
for(int i=0;i&lt;data.length();i++){
list.add(data.getString(i));
}
}
System.out.println(list);
}
}

Here I have got following error

Exception in thread &quot;main&quot; org.json.JSONException: A JSONObject text must begin with &#39;{&#39; at 3 [character 4 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.&lt;init&gt;(JSONObject.java:184)
at testingJson.main(testingJson.java:31)

From this we can identify that something missed-format with inline variable while tokenize that to JSON string

In JSON string the format must be like this [ { the JSON data } ] .

答案2

得分: 1

List<String> items = JsonPath.parse(inline).read("$.lighthouseResult.audits.network-requests.details.items");
<!-- 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>
英文:

If you only want to retrieve the JSON array items in whole JSON response, it can be easily done by using JsonPath as follows:

Code snippet

List&lt;String&gt; items = JsonPath.parse(inline).read(&quot;$.lighthouseResult.audits.network-requests.details.items&quot;);

Maven dependency

&lt;!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
    &lt;artifactId&gt;json-path&lt;/artifactId&gt;
    &lt;version&gt;2.4.0&lt;/version&gt;
&lt;/dependency&gt;

答案3

得分: 0

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

// 注意这里我们正在读取一个数组
JSONArray items = details.getJSONArray("items");

// 创建String列表,并从items JSONArray对象中添加元素到其中
List<String> itemsList = new ArrayList<>();
items.forEach(item -> itemsList.add(item.toString()));
英文:

Assuming you have the complete json response in inline variable, you can convert it to JSONObject and then keep on reading the child attributes.

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

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

// Create String list and add elements to it from items JSONArray object
List&lt;String&gt; itemsList = new ArrayList&lt;&gt;();
items.forEach(item -&gt; itemsList.add(item.toString()));

huangapple
  • 本文由 发表于 2020年10月15日 15:30:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64366803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定