JSON Stream parsing crashes at the end of the object

Viewed 194

I am struggling with some JSON parsing (with Google's GSON library).

Here is my minimal code example:

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

I get the following exception: (the string is 36 chars long)

Expected BEGIN_OBJECT but was END_DOCUMENT at line 1 column 37

My ReportAnalysis class looks like this:

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

I do not see why my code is not working. I followed the exmaple from Google

= = = EDIT = = =

The reader.hasNext() method always returns true. It seams that the method does not consume any tokens from the stream. But somehow still moves to the end of the stream and failes reading objects.

The problem was indeed the loop (facepalm). This works perfectly fine:

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

Thanks

1 Answers

I just removed loop and its working fine .

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());
Related