简体   繁体   English

使用gson解析JSON

[英]Parsing JSON by using 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
                }
            ]
        }
    }
}

I am trying to parse the following, I've tried many API, by using JSon in perl and JSon.simple, gson in Java without luck. 我试图解析以下内容,我尝试了许多API,方法是在perl中使用JSon和JSon.simple,而Java中的gson则没有运气。

What I am trying to parse out is facets=>pie=>terms=>term and count, can someone give me a hint on how to extract both values? 我要解析的是facets => pie => terms => term and count,有人可以给我提示如何提取两个值吗?

Here is what I have so far 这是我到目前为止的

    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)

Your JSON is OK. 您的JSON正常。 Here is a Perl snippet that prints out all terms and counts: 这是一个Perl片段,可打印出所有术语和计数:

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

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

Output: 输出:

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

The problem in your Java code is that the pie entry does not point to an JSON array, rather it contains an JSON object. 您的Java代码中的问题在于, pie条目未指向JSON数组,而是包含一个JSON对象。

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

Your probably wanted (untested, and debatable style): 您可能想要的(未经品尝且值得商de的风格):

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

gson GSON

    public static void main(String[] args) {

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

}

public static void parse(String jsonLine) {
    JsonObject root = new JsonParser().parse(jsonLine).getAsJsonObject();
    JsonArray terms = root.getAsJsonObject("facets").getAsJsonObject("pie")
            .getAsJsonArray("terms");

    for (int i = 0; i < terms.size(); i++) {
        JsonObject term = terms.get(i).getAsJsonObject();
        System.out.printf("%s - %s \n", term.get("term").toString(), term.get("count").toString());
    }

}

Perl Perl的

my $json = decode_json $input;

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

Above both worked for me, thanks for your help 以上两者都为我工作,谢谢您的帮助

JsonArray jarray = jobject.getAsJsonArray("pie");

"pie" is an object, but you are accessing it as an array. “派”是一个对象,但是您以数组的形式访问它。 First you should get the "pie" object then he array, which is "terms". 首先,您应该获得“ pie”对象,然后得到“ terms”数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM