使用默认反序列化器的一些功能在gson中实现自定义反序列化器

时间:2016-10-24 19:30:18

标签: java gson

我有一个JSON对象,它包含原始字段,如int和string,以及日期字段和时间字段(也作为字符串)。我的JSON考试:

{  
         "auditorium":"506",
         "beginLesson":"10:30",
         "date":"2016.09.12",
         "dayOfWeekString":"Monday",
         "discipline":"Math",
         "endLesson":"11:10",
         "kindOfWork":"Lesson",
         "lecturer":"John Smith"
      }

我正在使用GSON lib,我正在实现自定义反序列化器,因为我希望“beginLesson”和“endLesson”字段不是字符串,而是LocalTime(我正在使用JodaTime lib)。所以我得到这些字段并将它们转换为LocalTime,但我希望其他字段正常反序列化(如果我只是编写fromJson()方法,那么我的类中的每个字段都将在json中设置为相同的值)。是否有一种简单的方法可以自动反序列化这些字段?或者我唯一的方法就是写出很多像

这样的行

MyClass.auditorium = json.get("auditorium"); MyClass.kindOfWork = json.get("kindOfWork");

1 个答案:

答案 0 :(得分:1)

可以使用自定义SELECT students.firstname, students.lastname, students.tnumber, grades.tnumber FROM students, grades WHERE grades.tnumber=students.tnumber AND (grades.Grade='A' OR grades.Grade='B' OR grades.Grade='C') 处理LocalTime反序列化。请参考TypeAdapter课程。

1)日期格式设为“yyyy.MM.dd”

2)org.joda.time.LocalTime - 格式化程序“HH:mm”

主要方法: -

LocalTimeDeserializer

礼堂课程: -

public static void main(String[] args) {
        String jsonString = "{\"auditorium\":\"506\",\"beginLesson\":\"10:30\",\"date\":\"2016.09.12\",\"dayOfWeekString\":\"Monday\",\"discipline\":\"Math\",\"endLesson\":\"11:10\",\"kindOfWork\":\"Lesson\",\"lecturer\":\"John Smith\"}";
        Gson gson = new GsonBuilder().setDateFormat("yyyy.MM.dd")
                .registerTypeAdapter(LocalTime.class, new LocalTimeDeserializer()).create();

        Auditorium auditorium = gson.fromJson(jsonString, Auditorium.class);
        System.out.println(auditorium.toString());

    }

LocalTime反序列化程序: -

public class Auditorium implements Serializable{

    private static final long serialVersionUID = 6752903482239784124L;

    private final DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm");

    private String auditorium;
    private LocalTime beginLesson;
    private Date date;
    private String dayOfWeekString;
    private String discipline;
    private LocalTime endLesson;
    private String kindOfWork;
    private String lecturer;
    @Override
    public String toString() {
        return "Auditorium [auditorium=" + auditorium + ", beginLesson=" + beginLesson.toString(fmt) + ", date=" + date
                + ", dayOfWeekString=" + dayOfWeekString + ", discipline=" + discipline + ", endLesson=" + endLesson.toString(fmt)
                + ", kindOfWork=" + kindOfWork + ", lecturer=" + lecturer + "]";
    }

    ... getter and setters

}

<强>输出: -

public class LocalTimeDeserializer implements JsonDeserializer<LocalTime> {

    final DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm");

    @Override
    public LocalTime deserialize(JsonElement paramJsonElement, Type paramType,
            JsonDeserializationContext paramJsonDeserializationContext) throws JsonParseException {

        return LocalTime.parse(paramJsonElement.getAsString(), fmt);
    }

}