Search code examples
jsonresttestingwebtau

How to retrieve JSON from request body using WebTau?


  • I have sent a request to a REST servlet and it returns a JSON array

    • I need to get the JSON as a String for further processing.
  • Originally I used this to get the body:

    DataNode  result =  body.get("carList");`
    return result.toString();`
    
  • Then tried to parse the body, which is originally JSON, but ...

  • This string threw an exception from the Jackson library:

    "Unexpected character ('c' (code 99)): was expecting double-quote to start field name
      at [Source: (String)"[{carNumber: 22248002, trailerNumber: }]"; line: 1, column: 4]"
    
    • These are the expected values.
    • They are not in a recognised JSON form.
  • For the example above the requirement is: [ {"carNumber" : "1234", "trailerNumber" : "567"}, ... ]

  • I have not (yet) found an example or guide rooting about in the documentation.

    • I looked for things like getJson(), getRaw() and such. I'm convinved it must be there.
    • In this case I want the entries from the list to use for testing an update operation.

Looking forward to your response.


Solution

  • author of WebTau here, thank you for using it.

    To get the DataNode underlying value, return the node from the validation block. If the node represented object, than an instance of Map will be returned. List for JSON array and correspondent type like String, Boolean for simple values

    Map<String, ?> bodyAsMap = http.get("/end-point", ((header, body) -> {
        return body;
    }));
    

    Note that it is not JSON yet. At this point you can convert Map back to JSON using any standard libraries. Or use WebTau JsonUtils.serialize.

    Also worth noting that it is not the original response from the server, but rather parsed to DataNode, then to Map and then to String.

    If you need to validate that JSON confirms to a schema you can use it directly inside the validation block

    If you need original raw content, you can use undocumented http method

    public HttpResponse getToFullUrl(String fullUrl, HttpHeader requestHeader)
    

    object it returns has getTextContent() method to access originally received content.

    Could you please elaborate why do you need raw content access? If there is a useful pattern, it may be a good idea to enable it in WebTau natively.