Howto extract data from the JSON body of REST requ

2019-07-28 06:28发布

问题:

I'm writing a custom Handler for WSO2 ESB to construct authentication credentials based on input request content. Right now what I have is something like this:

public boolean handleRequest(MessageContext context) {
    // TODO: extract relevant information (clientId) from JSON request body
    String clientId;

    Map<String, String> headers = (Map<String, String>) ((Axis2MessageContext) context).getAxis2MessageContext().getProperty(
            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    setAuthorization(headers, clientId);

    return true;
}

I can't find documentation regarding howto access REST JSON request body inside the Synapse handler. Any ideas? Is possible to define a property before the handler runs and capture it with something like String clientId = (String)context.getProperty("clientId")?

回答1:

You can try following;

// Getting the json payload to string
String jsonPayloadToString = JsonUtil.jsonPayloadToString(((Axis2MessageContext) context).getAxis2MessageContext());
// Make a json object
JSONObject jsonBody = new JSONObject(jsonPayloadToString);