2

我想解析来自服务器的 http json 响应的大响应。创建响应文件的类是有害的,因为文件太大。我尝试使用gson,但没有效果

这是响应http://www.sendspace.pl/file/ff7257d27380cf5e0c67a33

我的代码:

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

我得到了例外:

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)
4

1 回答 1

0

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);
于 2013-04-11T10:26:44.517 回答