Search code examples
javajsonrestjerseygson

Converting ZonedDateTime type to Gson


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();

}    

Solution

  • I have fixed it,This is the code after updates

    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);
    
            Gson gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
                @Override
                public ZonedDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                    return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString());
                }
                }).create();
    
            Type listType =  new TypeToken<List<Scorefactor>>() {}.getType();
    
            List<Scorefactor> scorefactors = gson.fromJson(output,listType);