如何为gson方法创建对象工厂方法?

时间:2016-11-10 08:30:39

标签: java gson

我正在从JSON对象生成一个Student对象,但问题是当我创建这个对象时我还想更新它的“studentClass”字段。我更新了setStudentClass()方法,但我认为GSON不使用这个setter字段。如何为fromJson()方法创建工厂方法?

Student student = gson.fromJson(studentJSON.toString(), Student.class);
student.updateClassInfo();


public class Student{

   private String name;
   private String studentClass;

   //getters and setters

   public void updateClassInfo(){

      if(studentClass.equals("1"))
        studentClass = "starter";
      else if
      .....
   }

}

1 个答案:

答案 0 :(得分:1)

使用自定义反序列化器可以满足此要求。示例代码如下: -

主要方法: -

public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"studentClass\":\"1\"}";
        //String jsonString = "{\"name\":\"John\"}";

        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Student.class, new StudentModelDeserializer())
                .create();

        Student student = gson.fromJson(jsonString, Student.class);
        System.out.println(student.toString());

    }

<强>解串器: -

public class StudentModelDeserializer implements JsonDeserializer<Student> {

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

        String studentClass = null;
        if (paramJsonElement.getAsJsonObject().get("studentClass") != null) {
            studentClass = paramJsonElement.getAsJsonObject().get("studentClass").getAsString();
        }

        Student student = new Gson().fromJson(paramJsonElement.getAsJsonObject(), Student.class);

        if (studentClass != null) {
            if (studentClass.equals("1")) {
                student.setStudentClass("starter");
            }
        }

        return student;
    }

}

<强>输出: -

Student [name=John, studentClass=starter]

如果学生班级不存在,则输出:

Student [name=John, studentClass=null]