简体   繁体   中英

Working with JSON Response on Groovy and populating a Map with the response

I'm making a POST request to a URL with groovy (using HttpResponse - Unirest) and retrieving the response as a JSONObject.

Next, I'm creating a Map with that response, using:

Map<String, Object> myMap = new HashMap<>(response.toMap())

My JSON response is something like this (sorry for looking like a weird response, but I had to cut the sensible information):

{
    "responses": [
        {
            "took": 123,
            "timed_out": true,
            },
            "hits": {
                "total": 123,
                "max_score": null,
                "hits": [
                    {
                        "_source": {
                            "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum payloadType=JSONpayload=[{"some json payload here"}]
                }
            }
        ]
    ]
}

}

I have two questions regarding this:

1 - When I try to print the key and the values, the key is "responses" and all the other parts are values. Is this normal? I also can't use a put function to add values to map. Which means, my map is kinda funky at the moment and I can't seem to find a solution to work with this. Should I use another library or so? I don't mind using another one, I just need to find a way to have a map that I can work with.

2 - I need my map values to be trimmed to only present results after a specific String, in this case, I need my map to be populated with the JSON payload that comes after "payloadType=JSONpayload=" to store it in a variable and then work with that information. How can I achieve that? Is a regex enough to make it? I was thinking of using an iterator to iterate through all the values and then trim them to a variable. Is this a good solution for this case?

Sorry if something is confusing, but I'm still a newbie at Java and Groovy and it's my first assignment at the project.

Thanks!

You can map your response not to Map, but to your custom created object called POJO. Next, with library Jackon, or Gson parse this Json. In the end you can have access to each value in Json, and for exmaple using regexp, extract certain data from specific fields. This approach is long term approach, easy to tests and maintanance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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