I have rest service that return arraylist of object,and I have implemented jersy restful client to execute it,but I have problem in converting ZonedDateTime type to json so I get this error
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 231 path $[0].lastmodifieddate
How can i fix this problem?
lastmodifieddate column in entity
@Column(name = "lastmodifieddate")
private ZonedDateTime lastmodifieddate;
//getter and setter
rest service
@RequestMapping(value = "/getScoreFactor",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Scorefactor> getScoreFactor() throws JSONException {
return scoreService.getScoreFactor();
}
jersy restful client
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/adap/api/getScoreFactor");
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
String output = response.getEntity(String.class);
System.out.println("output--"+output);
Type listType = new TypeToken<List<Scorefactor>>() {}.getType();
List<Scorefactor> scorefactors = new Gson().fromJson(output,listType);
System.out.println(scorefactors);
} catch (Exception e) {
e.printStackTrace();
}
I have fixed it,This is the code after updates
There are at least two ways to achieve this:
1) Gson with JsonDeserializer
Little changes within your code:
Helper Class
2) Use MessageBodyReader & XMLAdapter
Changes for your Client implementation:
You might need to import jersey-json for this
Btw, why do you use 1.*?
Your Scorefactor
ZonedDateTime from / to String (recommended)
ZonedDateTime from / to Long
You could also build your own MessageBodyReader/MessageBodyWriter or use other implementations like Moxy.
I would like to recommend to use Jersey 2.*.
Hope this was helpful somehow. Have a nice day.
Your solution posted doesn't work because ZonedDateTime's Json serialization is not a Json primitive but a Json object that contains more than a single element. It needs to develop a bit and here is a completed solution: