還原序列化json串時限定欄位不可為空

來源:互聯網
上載者:User

標籤:json   java   gson   

    設計Json Api時,總會遇到將Json字串轉化為Java 對象,然後再處理商務邏輯。但對象中的某些欄位我們不希望它們為空白,這就需要我們對Java對象的欄位進行校正。如果對象中包含多級對象,這樣校正起來就非常麻煩。

    我使用Google的gson進行json的序列化和還原序列化操作,所以就想到gson是否具有這樣的過濾機制,查看了好久的api,無奈也沒有什麼收穫,所以就想到自己修改gson代碼,增加這樣一個功能。實現方式類似gson中的@SerializedName和@Expose等,採用註解實現。

首先聲明一個註解

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface NotNull {}

gson在解析json字串時,會將欄位資訊存在BoundField這個類中,在這個欄位增加NotNull欄位,標識該欄位是否不可為空。

private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {    Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();    if (raw.isInterface()) {      return result;    }    Type declaredType = type.getType();    while (raw != Object.class) {      Field[] fields = raw.getDeclaredFields();      for (Field field : fields) {        boolean serialize = excludeField(field, true);        boolean deserialize = excludeField(field, false);        // 判斷欄位是否有@NotNull註解        boolean notNull = field.getAnnotation(NotNull.class) != null;        if (!serialize && !deserialize) {          continue;        }        field.setAccessible(true);        Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());        BoundField boundField = createBoundField(context, field, getFieldName(field),            TypeToken.get(fieldType), serialize, deserialize, notNull);        // 後面代碼省略}

然後在給欄位賦值的時候檢查欄位值是否為null或者是否不包含該欄位,同時欄位的notNull還是true,如果這樣就拋出JsonSyntaxException異常

檢查欄位值是否為null:

    @Override void read(JsonReader reader, Object value)          throws IOException, IllegalAccessException {        Object fieldValue = typeAdapter.read(reader);        if (fieldValue == null && notNull) {            throw new JsonSyntaxException("field " + name + " should not be null");        }        if (fieldValue != null || !isPrimitive) {          field.set(value, fieldValue);        }      }

檢查是否包含該欄位:

    @Override public T read(JsonReader in) throws IOException {      if (in.peek() == JsonToken.NULL) {        in.nextNull();        return null;      }      T instance = constructor.construct();      try {        in.beginObject();        Set<String> fields = new HashSet<String>();        while (in.hasNext()) {          String name = in.nextName();          BoundField field = boundFields.get(name);          fields.add(name);          if (field == null || !field.deserialized) {            in.skipValue();          } else {            field.read(in, instance);          }        }        for (BoundField field : boundFields.values()) {            if (field != null && field.notNull && !fields.contains(field.name)) {                throw new JsonSyntaxException("field " + field.name + " should not be null");            }        }      } catch (IllegalStateException e) {        throw new JsonSyntaxException(e);      } catch (IllegalAccessException e) {        throw new AssertionError(e);      }      in.endObject();      return instance;    }

這樣,你在解析json字串到java 對象時,如果想限定某個欄位的值不能為null時,只要加上@NotNull註解即可。

代碼從這裡下載:https://github.com/Will-luffy/gson

PS: 由於沒有把gson的源碼完全看過來,對增加的功能也沒有完全充分的進行測試,如果有什麼問題,還請指正,謝謝。

本文出自 “落地的過境鳥” 部落格,謝絕轉載!

還原序列化json串時限定欄位不可為空

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.