Converting ZonedDateTime type to Gson

后端 未结 4 1936
梦谈多话
梦谈多话 2021-01-18 10:33

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

4条回答
  •  不要未来只要你来
    2021-01-18 10:43

    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:

    public Gson gson() {
        return new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new JsonDeserializer() {
            @Override
            public ZonedDateTime deserialize(JsonElement json, Type type,
                    JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    
                JsonObject jsonObj = json.getAsJsonObject();
    
                JsonObject dateTime = jsonObj.getAsJsonObject("dateTime");
                JsonObject date = dateTime.getAsJsonObject("date");
                int year = date.get("year").getAsInt();
                int month = date.get("month").getAsInt();
                int day = date.get("day").getAsInt();
    
                JsonObject time = dateTime.getAsJsonObject("time");
                int hour = time.get("hour").getAsInt();
                int minute = time.get("minute").getAsInt();
                int second = time.get("second").getAsInt();
                int nano = time.get("nano").getAsInt();
    
                JsonObject zone = jsonObj.getAsJsonObject("zone");
                String id = zone.get("id").getAsString();
    
                return ZonedDateTime.of(year, month, day, hour, minute, second, nano, ZoneId.of(id));
            }
        }).create();
    }
    

提交回复
热议问题