PageRenderTime 41ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/xiejuntao/xdesktop
Java | 84 lines | 52 code | 14 blank | 18 comment | 13 complexity | 634ba434f369499752b6ac936a78ca5a MD5 | raw file
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.alibaba.fastjson.serializer;
  17. import java.io.IOException;
  18. import java.lang.reflect.Type;
  19. /**
  20. * @author wenshao<szujobs@hotmail.com>
  21. */
  22. public class ArraySerializer implements ObjectSerializer {
  23. private final ObjectSerializer compObjectSerializer;
  24. public ArraySerializer(ObjectSerializer compObjectSerializer){
  25. super();
  26. this.compObjectSerializer = compObjectSerializer;
  27. }
  28. public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType)
  29. throws IOException {
  30. SerializeWriter out = serializer.getWriter();
  31. if (object == null) {
  32. if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
  33. out.write("[]");
  34. } else {
  35. out.writeNull();
  36. }
  37. return;
  38. }
  39. Object[] array = (Object[]) object;
  40. int size = array.length;
  41. int end = size - 1;
  42. if (end == -1) {
  43. out.append("[]");
  44. return;
  45. }
  46. SerialContext context = serializer.getContext();
  47. serializer.setContext(context, object, fieldName);
  48. try {
  49. out.append('[');
  50. for (int i = 0; i < end; ++i) {
  51. Object item = array[i];
  52. if (item == null) {
  53. out.append("null,");
  54. } else {
  55. compObjectSerializer.write(serializer, item, i, null);
  56. out.append(',');
  57. }
  58. }
  59. Object item = array[end];
  60. if (item == null) {
  61. out.append("null]");
  62. } else {
  63. compObjectSerializer.write(serializer, item, end, null);
  64. out.append(']');
  65. }
  66. } finally {
  67. serializer.setContext(context);
  68. }
  69. }
  70. }