JSON Stream解析在对象末尾崩溃

时间:2017-09-22 11:26:09

标签: java json gson

我正在努力进行一些JSON解析(使用Google的GSON库)。

这是我的最小代码示例:

Gson gson = new Gson();
String line = "{\"method\":\"GET\",\"status\":\"200 - OK\"}";
AnalysisReport report = gson.fromJson(line, AnalysisReport.class); //this works 




JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input

while (reader.hasNext()) {
      report = gson.fromJson(reader, AnalysisReport.class); //this doesn't work
}

reader.close();

我得到以下异常:(字符串长36个字符)

Expected BEGIN_OBJECT but was END_DOCUMENT at line 1 column 37

我的 ReportAnalysis 类如下所示:

public class AnalysisReport {
   @SerializedName("method")
    private String method;

    @SerializedName("status")
    private String status;

    AnalysisReport(){            
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getStatus() {
        return status;
    }  
}

我不明白为什么我的代码无效。我跟着Google

的例子

= = = EDIT = = =

reader.hasNext()方法始终返回true。它接缝表明该方法不会消耗流中的任何令牌。但不知何故,仍然会移动到流的末尾,并且会破坏读取对象。

问题确实是循环(facepalm)。这完全没问题:

JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input
report = gson.fromJson(reader, AnalysisReport.class);

由于

1 个答案:

答案 0 :(得分:1)

我刚刚移除了循环并且工作正常。

String line = "{\"method\":\"GET\",\"status\":\"200 - OK\"}";
AnalysisReport report = new AnalysisReport();
Gson gson = new GsonBuilder().create();
JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input

report = gson.fromJson(line, AnalysisReport.class); //this doesn't work

reader.close();
System.out.println(report.toString());