Java Gson http response difficult parsing

心不动则不痛 提交于 2019-12-24 08:38:56

问题


I want to parse big response from http json response from server. Creating class responding to file is harmful because file is too large. I tried with gson, but with no effect

Here is response http://www.sendspace.pl/file/ff7257d27380cf5e0c67a33

And my code :

try {
  JsonReader reader = new JsonReader(content);
  JsonElement json = new JsonParser().parse(reader);
  reader.beginObject();
  while (reader.hasNext()) {
    String name = reader.nextName();
    if (name.equals("devices")) {
      System.out.println("gfdd");
    } else {
      reader.skipValue(); //avoid some unhandle events
    }
  }
  reader.endObject();
  reader.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

I am getting exception:

Exception in thread "main" java.lang.IllegalStateException: Expected BEGIN_OBJECT but was END_DOCUMENT at line 799 column 2
    at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
    at LightsControl.main(LightsControl.java:41)

回答1:


In order to parse your JSON response with GSON, you need to create a number of classes to wrap your reponse.

In your case, you should have something like:

public class Response {

  @SerializedName("devices")
  private List<Device> devices;
  @SerializedName("scenes")
  private List<Scene> scenes;
  @SerializedName("sections")
  private List<Section> sections;
  //...other fields...

  //getter and setter
}

And then:

public class Device{

  @SerializedName("id")
  private String id;
  @SerializedName("name")
  private String name;
  @SerializedName("device_type")
  private String deviceType;
  @SerializedName("device_file")
  private String deviceFile;
  @SerializedName("states")
  private List<State> states;
  //... other fields

  //getters and setters
}

And then you have to do the same with classes Scene, Section, State and so on... Obviously it's a little tedious because your JSON response is very long with many different values...

The good thing is that you can easily skip values if you don't need them. For example, if you don't need to retrieve the states of a device, you can just remove the attribute states from the class Device and GSON automatically skip those values...

Then you just parse the JSON with your Reponse object, like this:

String jsonString = "your json data...";
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);


来源:https://stackoverflow.com/questions/15924550/java-gson-http-response-difficult-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!