PageRenderTime 38ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/serializer/EnumerationSeriliazer.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 75 lines | 60 code | 15 blank | 0 comment | 16 complexity | 0b527163c4413ad23aa3c04b9249f3da MD5 | raw file
  1. package com.alibaba.fastjson.serializer;
  2. import java.io.IOException;
  3. import java.lang.reflect.ParameterizedType;
  4. import java.lang.reflect.Type;
  5. import java.util.Enumeration;
  6. public class EnumerationSeriliazer implements ObjectSerializer {
  7. public static EnumerationSeriliazer instance = new EnumerationSeriliazer();
  8. public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
  9. SerializeWriter out = serializer.getWriter();
  10. if (object == null) {
  11. if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
  12. out.write("[]");
  13. } else {
  14. out.writeNull();
  15. }
  16. return;
  17. }
  18. Type elementType = null;
  19. if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
  20. if (fieldType instanceof ParameterizedType) {
  21. ParameterizedType param = (ParameterizedType) fieldType;
  22. elementType = param.getActualTypeArguments()[0];
  23. }
  24. }
  25. Enumeration<?> e = (Enumeration<?>) object;
  26. SerialContext context = serializer.getContext();
  27. serializer.setContext(context, object, fieldName);
  28. try {
  29. int i = 0;
  30. out.append('[');
  31. while (e.hasMoreElements()) {
  32. Object item = e.nextElement();
  33. if (i++ != 0) {
  34. out.append(',');
  35. }
  36. if (item == null) {
  37. out.writeNull();
  38. continue;
  39. }
  40. Class<?> clazz = item.getClass();
  41. if (clazz == Integer.class) {
  42. out.writeInt(((Integer) item).intValue());
  43. continue;
  44. }
  45. if (clazz == Long.class) {
  46. out.writeLong(((Long) item).longValue());
  47. if (out.isEnabled(SerializerFeature.WriteClassName)) {
  48. out.write('L');
  49. }
  50. continue;
  51. }
  52. ObjectSerializer itemSerializer = serializer.getObjectWriter(clazz);
  53. itemSerializer.write(serializer, item, i - 1, elementType);
  54. }
  55. out.append(']');
  56. } finally {
  57. serializer.setContext(context);
  58. }
  59. }
  60. }