Java Gson - 从JSON树获取特定值

时间:2018-03-13 01:06:21

标签: java json servlets gson

我有这个JSON:

request_time: "2018-03-13T00:59:44+00:00",
stops: [
{
atcocode: "370023715",
mode: "bus",
name: "AG1",
stop_name: "AG1",
smscode: "37023715",
bearing: "N",
locality: "Sheffield Centre",
indicator: "AG1",
longitude: -1.46616,
latitude: 53.38248,
distance: 57
},
{
atcocode: "370027281",
mode: "bus",
name: "AG12",
stop_name: "AG12",
smscode: "37027281",
bearing: "N",
locality: "Sheffield Centre",
indicator: "AG12",
longitude: -1.46583,
latitude: 53.38228,
distance: 77
}
]
}

我想在数组中检索并存储此子树中的每个位置和atocode。我目前有这个java代码,但它只显示子树中的所有内容:

JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    response.setContentType("text/html");
            PrintWriter  out  = response.getWriter();
            out.println("<html><body>");

    if (element.isJsonObject()){
        JsonObject bus = element.getAsJsonObject();

        JsonArray array = bus.getAsJsonArray("stops");
        for (int i = 0; i < array.size(); i++){
            out.println(array.get(i)); 

}

1 个答案:

答案 0 :(得分:1)

因此,只需在每个get数组元素上使用JsonObject "stops"方法:

public static void main(String[] args) {
    String json = "{request_time: \"2018-03-13T00:59:44+00:00\",\n" + "stops: [\n" + "{\n"
        + "atcocode: \"370023715\",\n" + "mode: \"bus\",\n" + "name: \"AG1\",\n"
        + "stop_name: \"AG1\",\n" + "smscode: \"37023715\",\n" + "bearing: \"N\",\n"
        + "locality: \"Sheffield Centre\",\n" + "indicator: \"AG1\",\n" + "longitude: -1.46616,\n"
        + "latitude: 53.38248,\n" + "distance: 57\n" + "},\n" + "{\n" + "atcocode: \"370027281\",\n"
        + "mode: \"bus\",\n" + "name: \"AG12\",\n" + "stop_name: \"AG12\",\n"
        + "smscode: \"37027281\",\n" + "bearing: \"N\",\n" + "locality: \"Sheffield Centre\",\n"
        + "indicator: \"AG12\",\n" + "longitude: -1.46583,\n" + "latitude: 53.38228,\n"
        + "distance: 77\n" + "}\n" + "]\n" + "}";

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    if (element.isJsonObject()) {
      JsonObject bus = element.getAsJsonObject();

      JsonArray array = bus.getAsJsonArray("stops");
      for (int i = 0; i < array.size(); i++) {
        System.out.println(((JsonObject) array.get(i)).get("locality"));
        System.out.println(((JsonObject) array.get(i)).get("atcocode"));
      }
    }
  }

输出:

"Sheffield Centre"
"370023715"
"Sheffield Centre"
"370027281"

P.S。我没有提供如何将这些存储在数组中的代码,因为不清楚你想要如何存储它,你想要多少个数组......