英文:
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 :
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 = "";
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");
}
}
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&key=YourAPIKeyHere&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 数据 } ]。
英文:
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 = "";
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);
}
}
Here I have got following error
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)
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<String> items = JsonPath.parse(inline).read("$.lighthouseResult.audits.network-requests.details.items");
Maven dependency
<!-- 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
得分: 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("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()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论