Parse JSON Object from URL in Groovy

20,772

Seems to me that you need a recent version of Groovy for this to work (2.2.1 seems to be OK but 2.1.9 is not). In the mean time (until Groovy is upgraded and if the data you are receiving is not too big) you could use something like this:

def card = new JsonSlurper().parseText(apiUrl.text)
Share:
20,772

Related videos on Youtube

AnthonyMDev
Author by

AnthonyMDev

Working at Salesforce.com as the Technical Lead of iOS on Philanthropy Cloud. Former iOS Product Performance Engineer @ Facebook Former Lead iOS Developer for App-Order.com LinkedIn

Updated on December 23, 2020

Comments

  • AnthonyMDev
    AnthonyMDev over 3 years

    I'm trying to parse the JSON object from the following API into groovy:

    http://mtgapi.com/api/v1/fetch/id/1?token=f1fc6636e6f25d97c007984f0c7fe5785b3e3482

    Here is my class:

    package mtgtournamentorganizer
    
    import groovy.json.JsonSlurper
    
    class GetCardService {
    
        String token = "?token=f1fc6636e6f25d97c007984f0c7fe5785b3e3482"
        String base = "http://mtgapi.com/api/v1/fetch/"
        String id = "id/"
        String cardId
        String apiString
    
        def getCardById(cardId) {
    
            apiString =base + id + cardId + token
    
            URL apiUrl = new URL(apiString)
    
            def card = new JsonSlurper().parse(apiUrl)
    
            return card
    
        }
    
    }
    

    When I call getCardById(1)

    I get this error:

    |  groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.net.URL) values: [http://mtgapi.com/api/v1/fetch/id/1?token=f1fc6636e6f25d97c007984f0c7fe5785b3e3482]
    Possible solutions: parse(java.io.Reader), use([Ljava.lang.Object;), wait(), any(), grep(), wait(long)
        at mtgtournamentorganizer.GetCardService.getCardById(GetCardService.groovy:21)