標籤: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串時限定欄位不可為空