PageRenderTime 51ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/resty-common/src/main/java/cn/dreampie/common/util/json/ModelSerializer.java

https://gitlab.com/xialeizhou/resty
Java | 61 lines | 49 code | 9 blank | 3 comment | 10 complexity | 29e49e78d7644e44681136aaf6031ac3 MD5 | raw file
  1. package cn.dreampie.common.util.json;
  2. import cn.dreampie.common.Entity;
  3. import cn.dreampie.common.util.Stringer;
  4. import com.alibaba.fastjson.JSONException;
  5. import com.alibaba.fastjson.annotation.JSONField;
  6. import com.alibaba.fastjson.serializer.JSONSerializer;
  7. import com.alibaba.fastjson.serializer.ObjectSerializer;
  8. import com.alibaba.fastjson.serializer.SerializeWriter;
  9. import java.io.IOException;
  10. import java.lang.reflect.Method;
  11. import java.lang.reflect.Type;
  12. import java.util.Map;
  13. /**
  14. * Created by ice on 14-12-31.
  15. */
  16. public enum ModelSerializer implements ObjectSerializer {
  17. INSTANCE;
  18. public static ModelSerializer instance() {
  19. return INSTANCE;
  20. }
  21. public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
  22. SerializeWriter write = serializer.getWriter();
  23. if (object == null) {
  24. write.writeNull();
  25. return;
  26. }
  27. String mName;
  28. if (object instanceof Entity) {
  29. Method[] methods = object.getClass().getDeclaredMethods();
  30. JSONField fieldAnn = null;
  31. for (Method m : methods) {
  32. fieldAnn = m.getAnnotation(JSONField.class);
  33. mName = m.getName();
  34. if ((fieldAnn == null || fieldAnn.serialize()) && mName.startsWith("get")
  35. && !hasMethod((Entity<?>) object, mName)) {
  36. try {
  37. m.invoke(object);
  38. } catch (Exception e) {
  39. throw new JSONException("Method could not invoke.", e);
  40. }
  41. }
  42. }
  43. serializer.write(((Entity<?>) object).getAttrs());
  44. }
  45. }
  46. private boolean hasMethod(Entity<?> object, String mName) {
  47. Map<String, Object> attrs = object.getAttrs();
  48. String name = mName.replace("get", "");
  49. return attrs.containsKey(Stringer.firstLowerCase(name))
  50. || attrs.containsKey(Stringer.underlineCase(name));
  51. }
  52. }