github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgRpc/kmgRpcJava/java/src/com/google/gson/internal/LazilyParsedNumber.java (about) 1 /* 2 * Copyright (C) 2011 Google Inc. 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.google.gson.internal; 17 18 import java.io.ObjectStreamException; 19 import java.math.BigDecimal; 20 21 /** 22 * This class holds a number value that is lazily converted to a specific number type 23 * 24 * @author Inderjeet Singh 25 */ 26 public final class LazilyParsedNumber extends Number { 27 private final String value; 28 29 public LazilyParsedNumber(String value) { 30 this.value = value; 31 } 32 33 @Override 34 public int intValue() { 35 try { 36 return Integer.parseInt(value); 37 } catch (NumberFormatException e) { 38 try { 39 return (int) Long.parseLong(value); 40 } catch (NumberFormatException nfe) { 41 return new BigDecimal(value).intValue(); 42 } 43 } 44 } 45 46 @Override 47 public long longValue() { 48 try { 49 return Long.parseLong(value); 50 } catch (NumberFormatException e) { 51 return new BigDecimal(value).longValue(); 52 } 53 } 54 55 @Override 56 public float floatValue() { 57 return Float.parseFloat(value); 58 } 59 60 @Override 61 public double doubleValue() { 62 return Double.parseDouble(value); 63 } 64 65 @Override 66 public String toString() { 67 return value; 68 } 69 70 /** 71 * If somebody is unlucky enough to have to serialize one of these, serialize 72 * it as a BigDecimal so that they won't need Gson on the other side to 73 * deserialize it. 74 */ 75 private Object writeReplace() throws ObjectStreamException { 76 return new BigDecimal(value); 77 } 78 }