Gson不遵守建造者的规则

时间:2016-02-25 09:13:54

标签: java json gson builder

我有一个名为Student的类,其中包含一些必填字段,其他字段是可选字段。为了确保在没有提供必填字段的情况下没有创建类Student的对象,我正在使用构建器。这是课程Student

package prj1.dob;

import java.util.Date;

public class Student {
   private final int id;
   private final String name;
   private final String surname;
   private final Date dob;
   private final Double gpa;
   private final String email;

   public static class Builder {
      //required fields
      private int id;
      private String name;
      private String surname;

      //optional fields
      private Date dob;
      private Double gpa;
      private String email;

      public Builder(int id, String name, String surname) {
         this.id = id;
         this.name = name;
         this.surname = surname;
      }

      public Builder dob(Date dob) {
         this.dob = dob;
         return this;
      }

      public Builder gpa(Double gpa) {
         this.gpa = gpa;
         return this;
      }

      public Builder email(String email) {
         this.email = email;
         return this;
      }

      public Student build() throws Exception {
         return new Student(this);
      }
    }

    private Student(Builder b) throws Exception {
         this.id = b.id;
         this.name = b.name;
         this.surname = b.surname;
         this.dob = b.dob;
         this.gpa = b.gpa;
         this.email = b.email;
         validate();
     }

   private void validate() throws Exception {
      if (id < 10 || name == null || surname == null) {
        throw new Exception("You should provide an id, name and surname.");
   }
 }

 @Override
 public String toString() {
  return "Student [id=" + id + ", name=" + name + ", surname=" + surname + ", dob=" + dob + ", gpa=" + gpa  + ", email=" + email + "]";
    }
}

实现类Student的这种实现,我希望不应该有一种创建无效Student对象的方法(即必填字段不应该是null)。但是,下面提供的代码不会抛出Exception,当我打印Student的内容时,必填字段为null

JSON对象:

{"id":-1,"name":null,"surname":null,"dob":null,"gpa":null,"email":null}

以下是从JSON创建POJO的代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try {
       String param = request.getParameter("std").toString();
       Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();
       Student student = gson.fromJson(param, Student.class);
       // student.validate();
       response.getWriter().write(student.toString());
  } catch (Exception ex) { 
       response.getWriter().write(ex.getMessage());
  }
}

我希望它会抛出一个Exception,但会创建一个Student的对象,打印时这是内容:

Student [id=-1, name=null, surname=null, dob=null, gpa=null, email=null]

这是Gson图书馆的一个错误,还是我做得不对?

如果它应该是这样的,那么当一个人仍然可以创建一个类的对象而不遵守规则(提供必需的字段)时,使用构建器方法有什么意义呢?

1 个答案:

答案 0 :(得分:3)

GSON使用reflection而不是您的构建器构建Student

虽然您无法阻止学生使用反射创建内容的其他用户,但您可以提供JsonDeserializer知道Student的规则并使用您的构建器创建一个。{/ p >