Transform body content before parsing
gtaylor1981 opened this issue · 2 comments
I'd like to be able to change the content of the response before it gets parsed.
This would be of help if the JSON that is returned is malformed in a known way, or if it has been encoded/encrypted.
Looking at the source code, a straightforward way to implement this might be to add an asJson(Function<String, String> transformer)
method.
For example, if a REST API returns { "result": 1234 } { "error": "none"}
It is recognised as invalid JSON so cannot be mapped by asJson()
.
Then I could write:
.post("url")
.asJson(jsonString -> jsonString.split(" \\{")[0])
This would be fine for my purposes but would work only for asJson()
and leaves the other API methods without this useful feature.
A more general approach (that works more like interceptors) might look like:
.post("url")
.transformRawResponse(rawResponse -> convert(rawResponse.getContentAsString().split(" \\{")[0]))
.asJson()
(Here, I'm not sure what the transformer should return so I used convert()
as a placeholder.)
The JSON Object has a public constructor so an easy way to do this would be:
JsonNode e = Unirest.get("http://localhost")
.asString()
.mapBody(b -> {
String newBody = b.split(" \\{")[0];
return new JsonNode(newBody);
});
Thanks for the suggestion, it's good enough to solve my problem.
I won't close this issue in case you think the generalised 'pre-transform' or asJson(transform)
suggestions are still worth investigating/implementing, otherwise feel free to close.
Thanks for your time.