java - 使用 gson 解析 JSON

标签 java json gson

{
    "took": 6200,
    "timed_out": false,
    "_shards": {
        "total": 68,
        "successful": 68,
        "failed": 0
    },
    "hits": {
        "total": 110745094,
        "max_score": 1,
        "hits": []
    },
    "facets": {
        "pie": {
            "_type": "terms",
            "missing": 135,
            "total": 29349,
            "other": 26420,
            "terms": [
                {
                    "term": "165.130.136.210",
                    "count": 390
                },
                {
                    "term": "165.130.136.206",
                    "count": 381
                },
                {
                    "term": "205.138.114.8",
                    "count": 359
                },
                {
                    "term": "205.138.115.229",
                    "count": 334
                },
                {
                    "term": "165.130.136.208",
                    "count": 331
                },
                {
                    "term": "66.37.212.155",
                    "count": 283
                },
                {
                    "term": "209.67.71.137",
                    "count": 279
                },
                {
                    "term": "66.37.204.17",
                    "count": 201
                },
                {
                    "term": "64.28.92.213",
                    "count": 193
                },
                {
                    "term": "64.85.64.202",
                    "count": 178
                }
            ]
        }
    }
}

我正在尝试解析以下内容,我已经尝试了很多 API,通过在 perl 中使用 JSon 和在 Java 中使用 JSon.simple,gson 但没有成功。

我要解析的是 facets=>pie=>terms=>term 和 count,有人可以提示我如何提取这两个值吗?

这是我目前的情况

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class TrueIPMonitor {

    public static void main(String[] args) {

        String json = getJson();
        System.out.println(json);
        System.out.println(parse(json));

    }

    public static String parse(String jsonLine) {
        JsonElement jelement = new JsonParser().parse(jsonLine);
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("facets");
        JsonArray jarray = jobject.getAsJsonArray("pie");
        jobject = jarray.get(0).getAsJsonObject();
        String result = jobject.get("terms").toString();
        return result;
    }

    public static String getJson() {
        BufferedReader br;
        String json = "";
        try {

            br = new BufferedReader(new FileReader("script/curlJson.log"));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
            json = sb.toString();

            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return json;

    }
}


{ "took" : 6200, "timed_out" : false, "_shards" : { "total" : 68, "successful" : 68, "failed" : 0 }, "hits" : { "total" : 110745094, "max_score" : 1.0, "hits" : [ ] }, "facets" : { "pie" : { "_type" : "terms", "missing" : 135, "total" : 29349, "other" : 26420, "terms" : [ { "term" : "165.130.136.210", "count" : 390 }, { "term" : "165.130.136.206", "count" : 381 }, { "term" : "205.138.114.8", "count" : 359 }, { "term" : "205.138.115.229", "count" : 334 }, { "term" : "165.130.136.208", "count" : 331 }, { "term" : "66.37.212.155", "count" : 283 }, { "term" : "209.67.71.137", "count" : 279 }, { "term" : "66.37.204.17", "count" : 201 }, { "term" : "64.28.92.213", "count" : 193 }, { "term" : "64.85.64.202", "count" : 178 } ] } } }

Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
    at com.google.gson.JsonObject.getAsJsonArray(JsonObject.java:172)
    at com.xxx.perf.monitor.TrueIPMonitor.parse(TrueIPMonitor.java:36)
    at com.xxx.perf.monitor.TrueIPMonitor.main(TrueIPMonitor.java:28)

最佳答案

您的 JSON 没问题。这是打印出所有项和计数的 Perl 片段:

...;
my $json = decode_json $input;

for my $term (@{ $json->{facets}{pie}{terms} }) {
    printf "%15s: %s\n", @$term{qw/term count/};
}

输出:

165.130.136.210: 390
165.130.136.206: 381
  205.138.114.8: 359
205.138.115.229: 334
165.130.136.208: 331
  66.37.212.155: 283
  209.67.71.137: 279
   66.37.204.17: 201
   64.28.92.213: 193
   64.85.64.202: 178

Java 代码中的问题是 pie 条目没有指向 JSON 数组,而是包含一个 JSON 对象。

facets : object
 `- pie : object
     `- terms : array

您可能想要的(未经测试且有争议的风格):

public static String parse(String jsonLine) {
    JsonObject root = new JsonParser().parse(jsonLine).getAsJsonObject();
    JsonArray terms = root.getAsJsonObject("facets").getAsJsonObject("pie").getAsJsonArray("terms")
    JsonOject firstTerm = terms.get(0).getAsJsonObject();
    String result = firstTerm.get("terms").toString();
    return result;
}

关于java - 使用 gson 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18322829/

相关文章:

python - 如何以扭曲的方式返回 json 响应?

java - 为什么 Java 不使用 GSON 将我的对象序列化为适当的 JSON 格式?

java - Gson 和 CSV 冲突?

java - 无法在Debian上安装默认的jdk包

java - 在 Java GUI 中更新 JTree

java - 如何在 Swing 中使用 GridLayout 使我的列大小不同?

java - 无法为JAX-B生成架构,仅在CORS调用REST服务期间发生

PHP 添加 mysql-results double 到数组。

php - Json 编码从 Ajax 中给我 null,但从正常的 php 字符串中没有给我 null

java - 使用 GSON 动态从 JsonArray 获取项目,无论类型是什么