java - 如何使用 GSON 迭代 JSON 数组并从中提取每个 JSON 对象?

标签 java gson arrays json

下面是我通过从服务 API 调用返回的 JSON 字符串。为了便于理解,我将其缩短为只有三个 reportRecords。一般来说,它可能有大约 500 个 reportRecords

{
   "aggRecords": {
      "reportRecords": [
         {
            "min": 0,
            "max": 12,
            "avg": 0.3699187,
            "count": 246,
            "sumSq": 571,
            "stddev": 1.4779372,
            "median": 0,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "PostProcessing",
               "Type": "PostProcessing"
            },
            "value": 91
         },
         {
            "min": 0,
            "max": 23,
            "avg": 2.3991289E-4,
            "count": 1463031,
            "sumSq": 3071,
            "stddev": 0.045814946,
            "median": 0,
            "percentileMap": {
               "95": 0
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "ResourceContext",
               "Type": "ResourceContext"
            },
            "value": 351
         },
         {
            "min": 0,
            "max": 1209,
            "avg": 1.9203402,
            "count": 7344636,
            "sumSq": 71832774,
            "stddev": 2.4683187,
            "median": 2,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "Client::Sync",
               "Type": "Client::Sync"
            },
            "value": 14104200
         }
      ]
   },
   "minRecordsMap": {}
}

现在,从上面的 JSON 响应中,我需要提取 NameClient::SyncreportRecords。这意味着,我只需要从上面的 JSON 响应中提取下面的 reportRecords

         {
            "min": 0,
            "max": 1209,
            "avg": 1.9203402,
            "count": 7344636,
            "sumSq": 71832774,
            "stddev": 2.4683187,
            "median": 2,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "Client::Sync",
               "Type": "Client::Sync"
            },
            "value": 14104200
         }

现在我需要将上面的 reportRecordsClient::Sync 解析到下面的对象 -

public class DataMetrics {

    private String pool;
    private String name;
    private String type;
    private String env;
    private String metricName;
    private String percentile;
    private String median;
    private String stdDev;
    private String sumSq;
    private String count;
    private String avg;
    private String max;
    private String min;

    // getters and setters here
}

上面的变量,像这样的映射 -

pool is titan
name is Client::Sync 
type is Client::Sync
env is dev
metricNname is TransactionDuration
95th  percentile is 4
median is 2
stdDev is 2.4683187 
sumSq is 71832774 
count is 7344636 
avg is 1.9203402
max is 1209
min is 0

我在这里使用 GSON 库,下面是我迄今为止尝试过的 -

private static RestTemplate restTemplate = new RestTemplate();

public static void main(String[] args) {

    String jsonLine = restTemplate.getForObject("some_url", String.class);
    System.out.println(jsonLine); // here jsonLine will give me above big JSON String

    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("aggRecords");
    JsonArray jarray = jobject.getAsJsonArray("reportRecords");

    // now how do I iterate JsonArray and get each JSON object
    // and then check "name" property of each object, if "Client::Sync" found, read that object for all properties
    // and set it using setters.

}

现在我无法理解如何迭代 JsonArray 并从中提取每个 JSON 对象?

最佳答案

因此,您拥有带有记录的 JsonArray 对象,以下是获取功能对象的操作:

Type type = new TypeToken<List<DataMetrics>>() {}.getType();
List<DataMetrics> records = gson.fromJson(jsonArrayThatYouHave, type);

然后您迭代对象并过滤您需要的对象。 在 java 8 中你可以这样做:

List<DataMetrics> result = records.stream().filter(record -> record.name.equals("Client::Sync")).collect(toList());

这种方法是转换所有对象并在之后进行迭代,如果这部分代码对性能至关重要,您仍然可以迭代 json 并仅转换必要的对象(但我怀疑这实际上会比上面描述的更快)。

无论如何,这是更易于维护和理解的代码。

更新:

对于 java 7 来说也是如此:

List<DataMetrics> result = new LinkedList<>();

for(DataMetrics record : records){
   if(record.name.equals("Client::Sync")){
      result.add(record);
   }
}

关于java - 如何使用 GSON 迭代 JSON 数组并从中提取每个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24257631/

相关文章:

java - 为什么非捕获组会改变正则表达式的行为?

javascript - 比较包含数组的对象属性以找出差异

java - 需要将 ArrayList 中的整数存储在尽可能少的容器中

java - 基于java的配置上的Spring Data CrudRepository - EntityManager - 没有事务正在进行

java - 没有日志的 UnableToCompleteException

java - Gson 不构造内部对象

java - Gson 反序列化为 Map 通用类型

java - GSON 和通用类型

c - 如何从c中的字符串数组中删除一个字符串

python - 如果条件为真则写入数组