简体   繁体   English

使用Java从Google自定义搜索输出已解析的JSON结果

[英]Outputting parsed JSON results from Google Custom Search in Java

I'm trying to output some results (title, url) from Google Custom Search in Java command line for testing, but I keep getting a java.io.EOFException error. 我正在尝试从Java命令行中的Google自定义搜索输出一些结果(标题,URL)以进行测试,但是我一直收到java.io.EOFException错误。 The compiler lists out the offending line, but I can't figure out what to change, even after spending hours searching for an answer. 编译器列出了有问题的行,但是即使花了数小时来寻找答案,我也无法弄清楚要更改的内容。 I took most of the code from an existing question here on Stack Overflow. 我从Stack Overflow上现有的问题中提取了大部分代码。 Any help is appreciated. 任何帮助表示赞赏。

package google.api.search;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.Gson;

class GSearch {

public static void main(String args[]) throws IOException  {
   String key = ""; //replace with API key
   String qry = ""; // search key word
   String cx = ""; //replace with cx
   URL url = new URL ("https://www.googleapis.com/customsearch/v1?key=" +key+ "&cx=" +cx+ "&q=" +qry+ "&alt=json");

   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Accept","application/json");
   BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );

   String output;
   {while ((output = br.readLine()) != null){
       GResults results = new Gson().fromJson(output, GResults.class);
       System.out.println(results);
   }   
   conn.disconnect(); 
   }  
   }
}

GResults class: GResults类:

public class GResults {

String title;
String link;

public GResults(String title, String link) {
    this.title = title;
    this.link = link;
}

public String getTitle(){
    return title;
}

public String getLink(){
    return link;
}

public void setTitle(String title){
    this.title = title;
}

public void setLink(String link){
    this.link = link;
}

public String toString(){
    return ("Title:%s, Link:%s", title, link);
}   
}

Error line: 错误行:

GResults results = new Gson().fromJson(output, GResults.class);

Error messages: 错误讯息:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at google.api.search.GSearch.main(GSearch.java:26)
Caused by: java.io.EOFException: End of input at line 1 column 2
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1377)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:483)
at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:403)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.Gson.fromJson(Gson.java:803)
... 4 more

I think I read it around 20 times before I noticed, Here is proper code 我想我在注意到之前大约阅读了20次,这是正确的代码

    final StringBuilder builder = new StringBuilder(50);
    String output;
    while ((output = br.readLine()) != null) {
        builder.append(output);
    }   
 final  GResults results = new Gson().fromJson(builder.toString(), GResults.class);

Gson is throwing proper exception because you were reading line by line and giving that line to gson for de-serializing. Gson抛出了适当的异常,因为您正在逐行阅读并将该行交给gson进行反序列化。 For example first line is { or [ or "message": { , and This is not a valid json JsonSyntax. 例如,第一行是{或[或“ message”:{,并且这不是有效的json JsonSyntax。

Enjoy :) 请享用 :)

I finally figured out the main flaw after going through the raw JSON output. 经过原始的JSON输出后,我终于找出了主要缺陷。 Google's JSON was returning an array of "items" instead via the [] symbols, so after adding a List in the GResults class as so: Google的JSON通过[]符号返回了一个“项目” 数组 ,因此在GResults类中添加了一个List之后:

import java.util.List;

public class GResults {

public String link;
public List<GResults> items;

public String getLink(){
    return link;
}

public List<GResults> getItems(){
    return items;
}

public void setLink(String link){
    this.link = link;
}

public void setGroups(List<GResults> items){
    this.items = items;
}

public void getThing (int i){
    System.out.println(items.get(i));
}

public String toString(){
    return String.format("%s", link);
}

}

I was able to return a series of links with the following command in the main GSearch class: 我可以在主GSearch类中使用以下命令返回一系列链接:

   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Accept","application/json");
   BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );
   GResults results = new Gson().fromJson(br, GResults.class);

   for (int i=0; i<10; i++)
   results.getThing(i);

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

相关问题 将Twitter搜索结果中的JSON字符串获取到Java中进行解析 - Getting the JSON string from a Twitter search result into Java to be parsed Java是否返回没有自定义搜索API的Google URL结果列表? - Java Return a List of Google URL Results without Custom Search API? 如何从Java中的Google搜索中排除搜索结果(链接) - How to exclude the search results (Links) from a google search in Java 如何从Google自定义Api搜索返回的Json中获取Java对象 - How to get Java Object from Json returned by Google Custom Api search 将JSON转换为Java中的类时出现问题(Google自定义搜索) - Problem in Converting json to class in java ( google custom search) Selenium Java代码打印google搜索的前五个结果 - Selenium Java code to print the first five results from google search Java Selenium如何从Google搜索结果中打开链接? - Java selenium how to open a link from google search results? 如何通过Google自定义搜索API创建JSON对象? - How to create a JSON object from Google Custom Search API? Java:将使用Jsoup解析的多个文件的结果写入文本文件 - Java : write results from multiple files parsed with Jsoup to text file 如何在从Java Object解析的json数组中添加Json头 - how to add Json header in json array parsed from Java Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM