1

there is such a JSON: https://restcountries.com/v3.1/all I just want to have a choice "translations" -> "ita" -> "common"

HTTPBuilder getHttpBuilder() {
    new HTTPBuilder('https://restcountries.com/')
}

def http = httpBuilder.request(Method.GET, ContentType.JSON){
    uri.path = 'v3.1/all'
    uri.query = [fields: 'translations,ita,common']
    response.success = { resp, json ->
        log.error(json.toString()) //string
        log.error(JsonOutput.toJson(json).br) //json
        log.error(JsonOutput.prettyPrint(JsonOutput.toJson(json))) //formated json
    }
}

but I always get either a general view or nothing of what is needed Help me to understand! Thank you!

TheShestov
  • 11
  • 4
  • Please edit your question and provide example of expected result. – daggett Dec 08 '22 at 11:41
  • @daggett Hello! Thanks for answering. What does your comment imply? How exactly should I edit the question so that it meets the requirements? I wrote that I need to get a common from an available API What else should I write?? – TheShestov Dec 08 '22 at 16:15
  • how expected result of your code should look like? because i can't understand what you want to do. there is no such fields: `ita,common` in response – daggett Dec 08 '22 at 17:13
  • @daggett The code given in the example doesn't really reflect what could lead to the result :) If you go to: https://restcountries.com/v3.1/all you can see these fields: "common": "Mauritania" for example: "ita": { "official": "Repubblica islamica di Mauritania", "common": "Mauritania" – TheShestov Dec 08 '22 at 17:45
  • As I can see by documentation of this API you can filter only top-level fields. Any sublevel field access you should do in your code. – daggett Dec 09 '22 at 06:46

1 Answers1

0

Found this solution for me. Maybe someone else will stumble upon it too.

import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import groovy.json.JsonSlurper

HTTPBuilder getHttpBuilder() {
    new HTTPBuilder('https://restcountries.com/')
}

def http = httpBuilder.request(Method.GET, ContentType.JSON){
    uri.path = 'v3.1/all'    
}

def tempJson = JsonOutput.toJson(http)
def resultParseJson = parseJsonText(tempJson)
def needResult = resultParseJson.translations.ita.common

def parseJsonText(String textJson){
    def jsonSlurper = new JsonSlurper()
    return jsonSlurper.parseText(textJson)
}

needResult - what I need. Perhaps someone will have a more beautiful or correct solution - I will be grateful. But so far this result is satisfactory.

TheShestov
  • 11
  • 4