PageRenderTime 46ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/xiejuntao/xdesktop
Java | 58 lines | 32 code | 8 blank | 18 comment | 10 complexity | 0f53fe7ea1addeb0b33fca1581aa35aa 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 DoubleSerializer implements ObjectSerializer {
  23. public final static DoubleSerializer instance = new DoubleSerializer();
  24. public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
  25. SerializeWriter out = serializer.getWriter();
  26. if (object == null) {
  27. if (serializer.isEnabled(SerializerFeature.WriteNullNumberAsZero)) {
  28. out.write('0');
  29. } else {
  30. out.writeNull();
  31. }
  32. return;
  33. }
  34. double doubleValue = ((Double) object).doubleValue();
  35. if (Double.isNaN(doubleValue)) {
  36. out.writeNull();
  37. } else if (Double.isInfinite(doubleValue)) {
  38. out.writeNull();
  39. } else {
  40. String doubleText = Double.toString(doubleValue);
  41. if (doubleText.endsWith(".0")) {
  42. doubleText = doubleText.substring(0, doubleText.length() - 2);
  43. }
  44. out.append(doubleText);
  45. if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
  46. out.write('D');
  47. }
  48. }
  49. }
  50. }