2

Hi and thank you for reading.

I have to call a restful service via the Play framework and parse the json result to an object list. My problem is there are thousands of resources for creating a restful service with play but not much about the other direction.

My next problem is I'm only able to find examples of service calls in controllers. Is it a bad idea to call the service from a model? How would I call this service (without the need for a result)? This is what I have found so far.

return async(
    WS.url("http://localhost:3021/Dashboard.svc/Conversation").get().map(
        new Function<WS.Response, Result>() {
            public Result apply(WS.Response response) {
                return ok(response.asJson());
            }
        }
    )
);

I'm new to Play, so forgive me if I ask stupid questions. I feel better with c# at the moment.

Thanks in advance! Ben

1 Answer 1

1

Found it. Or - found how to do it. Not if it is a good idea to do how I did.

import play.libs.WS;
import play.*;
import play.mvc.*;
import play.mvc.Result.*;
import play.libs.F.Promise;
import play.libs.F.Function;

import java.util.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class Order {

...

    public static List<Order> getOrders() {
        String hostUri = Helper.getWsHostUri();

        Promise<WS.Response> promise = WS.url(hostUri + "Orders").get();
        Promise<List<Order>> promisedResult = promise.map(
            new Function<WS.Response, List<Order>>() {
                public List<Order> apply(WS.Response response) {
                    JsonNode json = response.asJson();
                    ArrayNode results = (ArrayNode)json;

                    List<Order> orders = new ArrayList<Order>();
                    Iterator<JsonNode> it = results.iterator();

                    while (it.hasNext()) {
                        JsonNode node  = it.next();
                        Order order = new Order();

                        order.from = node.get("From").asText();
                        order.contact = node.get("Contact").asText();
                        order.amount = node.get("Amount").asDouble();
                        order.status = node.get("Status").asInt();

                        orders.add(order);
                    }

                    return orders;
                }
            }
        );

        return promisedResult.get();
    }
}

I would still be glad to see how to do it if you are not guessing like myself ...

Thanks and have a nice day!

Ben

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.