java - 将 ZonedDateTime 类型转换为 Gson

标签 java json rest jersey gson

我有返回对象数组列表的休息服务,我已经实现了 jersy restful 客户端来执行它,但是我在将 ZonedDateTime 类型转换为 json 时遇到问题所以我得到这个错误

 Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 231 path $[0].lastmodifieddate

我该如何解决这个问题?

实体中的 lastmodifiedate 列

 @Column(name = "lastmodifieddate")
 private ZonedDateTime lastmodifieddate;

 //getter and setter

休息服务

@RequestMapping(value = "/getScoreFactor",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Scorefactor> getScoreFactor() throws JSONException {
    return scoreService.getScoreFactor();
}   

jersy restful 客户端

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

}    

最佳答案

public static final Gson GSON = new GsonBuilder()
    .registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() {
        @Override
        public void write(JsonWriter out, ZonedDateTime value) throws IOException {
            out.value(value.toString());
        }

        @Override
        public ZonedDateTime read(JsonReader in) throws IOException {
            return ZonedDateTime.parse(in.nextString());
        }
    })
    .enableComplexMapKeySerialization()
    .create();

关于java - 将 ZonedDateTime 类型转换为 Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36408192/

相关文章:

java - Websphere Liberty Profile for Eclipselink 上的 VerifyError

java - java中构造函数的值存储在哪里?

java - 如何向php发送数据?

java - Restful PUT 方法的 ModelAttribute 未填充值 ( JSON )

java - JAX-RS/REST 资源究竟是什么?

java - 如何解决数字格式异常?

java - 将图像旋转 90 度或倍数的更快方法

java - Android JSON 限制行数

ruby-on-rails - 使用 Ruby/Rails 进行 base 64 URL 解码?

c# - ASP.NET Web API 可以处理具有不同 Controller 的子资源吗