Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON Object from URL in Groovy

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)
like image 982
AnthonyMDev Avatar asked Dec 22 '13 20:12

AnthonyMDev


1 Answers

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)
like image 72
zoran119 Avatar answered Oct 28 '22 01:10

zoran119