简体   繁体   中英

Consuming a RestAPI JSON in grails 2.3.x

I am new to grails and I am learning. I want to consume a webservice API(Rest). I searched for the example but didn't get a good one. My requirement is: The address to consume is eg:localhost:8080/order/createOrder; which will provide the JSON. My JSON format will be :

  //and from JSON is:
username: 'abc',
        password: 'xyz',
        order: {
         orderDate
            orderNumber
            subTotal
            shipping
            discount
            netTotalPaid
            creditApplied
           transactionId
           specialInstruction
        }

I have to get the username,password and Order from JSON. Order is a Domain class where I will set the data from JSON.

Please suggest me with a detail explanation.

And if the JSON is not REST service,ieThe application itself provides JSON as a service ? , if we don't need to consume a REST service ?

Getting the JSON

Again, a few options. I like to use the REST Client Builder Plugin for this sort of thing. It comes with lots of utility methods to make your life easier.

For example, to get the JSON from your end point, it would be something like:

def resp = rest.get("http://grails.org/api/v1.0/plugin/acegi/")
def myJson = resp.json;

Using the JSON

There's a few options.

If Order is a domain class that maps to these values exactly, then you can use the GSON plugin. This enables the serialization and de serialization of POJOs (or grails Domain objects). An example of the usage is:

Gson gson = new GsonBuilder().create()

Order myOrder = gson.fromJson(myJsonData, Order.class)

println myOrder

Or if you want to keep things Grails, you can use the converters..

def myOrder = new Order(request.GSON);

Personally, I prefer the former.

Design Tips

  • Don't put all this stuff in a controller. Abstract it out to a service, so that your controller simply passes it off to the service layer and doesn't care what happens to it.

  • Put your URLs to the RESTful service in some sort of object, or string. If you change API endpoints, you don't want to have to update it all over your application.

Extra Reading

  • The GSON plugin home is where you can find the dependency to add to your build config.

  • The Docs will show you how to use the GSON plugin.

  • And these Docs will show you how to use the REST Client Builder Plugin.

I guess this will help..

def restBuilder = new RestBuilder()
def resp = restBuilder.get("http://localhost:8080/order/createOrder")
JSONObject mapData = data.getJSONObject(resp.json)
JsonSlurper slurper = new JsonSlurper()
def object = slurper.parseText(mapData.toString())
def order = Order(object)

Here Order is pojo class

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