Nico Nico - 4 months ago 46
HTTP Question

String to Response (http) in Java

I have a webservice call that receives a "Response" object but i am only able to receive it as a string, like the next one:

<200 OK,{"id":0,"amount":10000,"type":"Normal","userId":0,"userIdTeller":0,"createdAt":"15/12/2016 12:08","branchOfficeyId":0},{Server=[Apache-Coyote/1.1], Access-Control-Allow-Origin=[*], Access-Control-Allow-Methods=[*], Access-Control-Allow-Headers=[*], Access-Control-Max-Age=[86400], Content-Type=[application/json], Transfer-Encoding=[chunked], Date=[Sun, 16 Oct 2016 13:21:02 GMT]}>

So, i am interested in the first part
<200 OK
and the second part
{"id":0,"amount":10000,"type":"Normal","userId":0,"userIdTeller":0,"createdAt":"15/12/2016 12:08","branchOfficeyId":0}
. I could easely split with
and take the first two elements, but if you know a class to unmarshall this string it would be better.

Best Regards!


You can create a custom user defined bean class that would hold the details of your response entity object like id, amount etc along with its getters and setters

I would suggest using RestTemplate in the below fashion where your client code is being used.

Suppose that the JSON equivalent Java object are instances of MyResponse you can make use of the below client code.

private void getMyResponse()
    final String uri = "theRestWebServiceURI";
    RestTemplate restTemplate = new RestTemplate();

    MyResponse myResponse = restTemplate.getForObject(uri, MyResponse.class);


Note that you may have to add Jackson Dependencies as Spring RestTemplate would be making use of its API for marshalling/un-marshalling JSON into Java objects and vice versa.