【问题标题】:Outputting parsed JSON results from Google Custom Search in Java从 Java 中的 Google 自定义搜索输出解析的 JSON 结果
【发布时间】:2013-12-07 12:51:07
【问题描述】:

我正在尝试在 Java 命令行中从 Google 自定义搜索中输出一些结果(标题、网址)以进行测试,但我不断收到 java.io.EOFException 错误。编译器列出了有问题的行,但我不知道要改变什么,即使花了几个小时寻找答案。我从 Stack Overflow 上的一个现有问题中获取了大部分代码。任何帮助表示赞赏。

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 类:

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

错误行:

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

错误信息:

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

【问题讨论】:

  • 能否请您发布完整的堆栈跟踪以及出现错误的行?
  • 我已按要求添加了错误消息。

标签: java json gson google-custom-search


【解决方案1】:

我想我读了大约 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 正在抛出适当的异常,因为您正在逐行读取并将该行提供给 gson 以进行反序列化。例如第一行是 { 或 [ 或 "message": { ,这不是一个有效的 json JsonSyntax。

享受:)

【讨论】:

  • 试了一下,又报错:Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 14813 这行代码:final GResults results = new Gson().fromJson(builder.toString(), GResults.class);
  • 我认为您的 JSON 格式不正确,您需要检查您的 json 格式是否有效,请转到此处jsonformatter.curiousconcept.com。你能在这里发布你的 json 示例吗
  • @gwar666 当对象末尾有非空格的额外字符时,GSON 会抛出该特定错误 - 并且它非常狭窄地定义了空格(正如 JSON 规范所做的那样) - 只有 \t, \ n、\r 和空格算作空白。如果你不能轻易找出导致多余字符的原因并消除它们,另一种选择是告诉 GSON 以宽松模式解析: Gson gson = new Gson(); JsonReader reader = new JsonReader(new StringReader(result1)); reader.setLenient(true);
  • 我直接从 Google 自定义搜索 API 获取 JSON。我会尝试实现 GSON 宽松模式。
  • 试试这个 Gson gson = new Gson(); JsonReader reader = new JsonReader(new StringReader(builder.toString())); reader.setLenient(true); GResults 结果 = gson.fromJson(reader, GResults.class);
【解决方案2】:

在查看原始 JSON 输出后,我终于找出了主要缺陷。谷歌的 JSON 是通过 [] 符号返回一个 array 的“项目”,所以在 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);
}

}

我能够在主 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多