All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.leancloud.gson.MapDeserializerDoubleAsIntFix Maven / Gradle / Ivy

package cn.leancloud.gson;

import com.google.gson.*;
import com.google.gson.internal.LinkedTreeMap;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapDeserializerDoubleAsIntFix implements JsonDeserializer> {

  @Override  @SuppressWarnings("unchecked")
  public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return (Map) read(json);
  }

  public Object read(JsonElement in) {

    if(in.isJsonArray()){
      List list = new ArrayList();
      JsonArray arr = in.getAsJsonArray();
      for (JsonElement anArr : arr) {
        list.add(read(anArr));
      }
      return list;
    }else if(in.isJsonObject()){
      Map map = new LinkedTreeMap();
      JsonObject obj = in.getAsJsonObject();
      Set> entitySet = obj.entrySet();
      for(Map.Entry entry: entitySet){
        map.put(entry.getKey(), read(entry.getValue()));
      }
      return map;
    }else if( in.isJsonPrimitive()){
      JsonPrimitive prim = in.getAsJsonPrimitive();
      if(prim.isBoolean()){
        return prim.getAsBoolean();
      }else if(prim.isString()){
        return prim.getAsString();
      }else if(prim.isNumber()){

        Number num = prim.getAsNumber();
        // here you can handle double int/long values
        // and return any type you want
        // this solution will transform 3.0 float to long values
        double doubleValue = Math.ceil(num.doubleValue());
        if (doubleValue == num.intValue()) {
          return num.intValue();
        } else if(doubleValue  == num.longValue()) {
          return num.longValue();
        } else {
          return num.doubleValue();
        }
      }
    }
    return null;
  }
}