使用嵌套对象访问jsonpath元素 [英] Accessing jsonpath elements with nested objects

查看:120
本文介绍了使用嵌套对象访问jsonpath元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从数组和对象的JSON路径中提取某些值,并将这些值用于进一步处理的过程,并且正在努力访问这些元素.这是JSON响应:

I am looking to extract certain values from a JSON path of arrays and objects and use these values for further processing and am struggling with accessing those elements. Here is the JSON response:

[  
 {  
  "od_pair":"7015400:8727100",
  "buckets":[  
     {  
        "bucket":"C00",
        "original":2,
        "available":2
     },
     {  
        "bucket":"A01",
        "original":76,
        "available":0
     },
     {  
        "bucket":"B01",
        "original":672,
        "available":480
     }
    ]
    },
 {  
  "od_pair":"7015400:8814001",
  "buckets":[  
     {  
        "bucket":"C00",
        "original":2,
        "available":2
     },
     {  
        "bucket":"A01",
        "original":40,
        "available":40
     },
     {  
        "bucket":"B01",
        "original":672,
        "available":672
     },
     {  
        "bucket":"B03",
        "original":632,
        "available":632
     },
     {  
        "bucket":"B05",
        "original":558,
        "available":558
     }
    ]
 }
]

我尝试使用$访问根元素,但无法继续使用.

I tried accessing the root elements with $ but I could not get further with it.

这是我编写的测试方法.我想提取od_pair的值,并在每个od_pair中,我需要能够检索存储桶代码及其可用数字.

Here is the test method that I have written. I want to extract the value for od_pair and within each od_pair, I need to be able to retrieve the bucket codes and their available numbers.

public static void updateBuckets(String ServiceName, String DateOfJourney) throws Exception {
    File jsonExample = new File(System.getProperty("user.dir"), "\\LogAvResponse\\LogAvResponse.json");
    JsonPath jsonPath = new JsonPath(jsonExample);

    List<Object> LegList = jsonPath.getList("$");
    // List<HashMap<String, String>> jsonObjectsInArray = jsonPath.getList("$");

    int NoofLegs = LegList.size();
    System.out.println("No of legs :" + NoofLegs);
    for (int j = 0; j <= NoofLegs; j++)
    // for (HashMap<String, String> jsonObject : jsonObjectsInArray) {
    {

        String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
        // String OD_Pair = jsonObject.get("od_pair");

        System.out.println("OD Pair: " + OD_Pair);
        List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");

        int NoOfBuckets = BucketsList.size();
        // System.out.println("OD Pair: " + OD_Pair);
        System.out.println("no of Buckets: " + NoOfBuckets);

        for (int i = 0; i < NoOfBuckets; i++) {
            String BucketCode = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].bucket");
            String Available = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].available");

            int BucketCodeColumn = XLUtils.getBucketCodeColumn(BucketCode);
            int ServiceRow = XLUtils.getServiceRow(ServiceName, DateOfJourney, OD_Pair);
            System.out.println("Row of " + ServiceName + ":" + DateOfJourney + "is:" + ServiceRow);
            System.out.println("Bucket Code column of " + BucketCode + " is: " + BucketCodeColumn);
            XLUtils.updateAvailability(ServiceRow, BucketCodeColumn, Available);
        }
    }

}

}

这是我看到的错误:

Caused by: 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup 
failed:
Script1.groovy: 1: unexpected token: [ @ line 1, column 27.
restAssuredJsonRootObject.[j].od_pair

有人可以帮我吗?

推荐答案

我建议将JSON解析为Java类以简化处理.

I would suggest parsing your JSON into Java classes to ease the processing.

该怎么做? 首先,我们需要创建Java类,以表示您提供的JSON.

How to do that? First, we need to create Java classes which will represent the JSON you provided.

让我们分析JSON. 从数组开始.该数组包含多个JSON对象.这些对象包含od_pair值和称为buckets的对象数组.

Let's analyze the JSON. Starts with an array. The array contains multiple JSON Object. These objects contain od_pair value and array of objects called buckets.

让我们创建一个类(您可以随意命名)Pair

Let's create a class (you can name it whatever you want) Pair

public class Pair {
    public String od_pair; //this name is important because it corresponds with the json element's name!
    public List<BucketObject> buckets; //same here!
}

此类表示主数组中的单个JSON对象.它包含od_pair值和嵌套的JSON数组,但以Java表示形式-> BucketObject类的列表.让我们创建BucketObject类:

This class represents a single JSON Object in the main Array. It contains od_pair value AND nested JSON Array but in Java representation -> List of BucketObject classes. Let's create BucketObject class:

public class BucketObject { //this name is NOT importnat
    public String bucket; //names are important
    public int original;
    public int available;
}

每个对象中只有3个值.

We have only 3 values in each of the objects.

现在,是时候将JSON解析为书面类了.

Now, it's time to parse JSON into the written classes.

JsonPath path = JsonPath.from(json);
Pair[] pairs = path.getObject("$", Pair[].class);

请记住,Pair是单个JSON对象.这就是为什么我们从以美元符号$表示的根开始解析,并声明将JSON解析为Pair对象的数组!

Remember that Pair is a single JSON Object. That's why we start parsing from the root represented by dollar sign $ and we declare that JSON should be parsed into an ARRAY of Pair objects!

现在,处理将变得更加简单!

Now, processing will be much simpler!

我不确定您需要什么,但是我将向您展示一个示例,该示例基于od_pair字段如何从存储桶中获取数据,您应该能够弄清楚其余的处理过程.

I am not sure what do you need, but I will show you an example of how to get data from the buckets based on od_pair field and you should be able to figure out the rest of the processing.

因此,我们有Pair类的数组:Pair[] pairs;

So, we have the array of Pair class: Pair[] pairs;

现在,我们要基于od_pair值获得1个Pair对象.

Now, we want to get 1 Pair object based on od_pair value.

    public static Pair getPairBasedOnOdPairValue(Pair[] pairs, String odPairValue) {
        for (Pair pair : pairs) {
            if (pair.od_pair.equals(odPairValue)) return pair;
        }

        throw new NoSuchElementException();
    }

现在,我们有了Pair对象.我们可以使用

Now, we have the Pair object. We can access buckets for this object using

List<BucketObject> buckets = pair.buckets;

其余的处理过程是在List<BucketObject>上迭代并获得所需的值.

The rest of the processing is iterating over List<BucketObject> and getting desired values.

希望有帮助!

这篇关于使用嵌套对象访问jsonpath元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆