Example usage for com.google.gson JsonPrimitive getAsNumber

List of usage examples for com.google.gson JsonPrimitive getAsNumber

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsNumber.

Prototype

@Override
public Number getAsNumber() 

Source Link

Document

convenience method to get this element as a Number.

Usage

From source file:adams.data.report.ReportJsonUtils.java

License:Open Source License

/**
 * Creates a report from the JSON object.
 *
 * @param jobj   the object to get the data from
 * @return      the report, null if failed to create or find data
 *//*  ww  w.j  av a 2 s  .  com*/
public static Report fromJson(JsonObject jobj) {
    Report result;
    Field field;
    JsonPrimitive prim;

    result = new Report();
    for (Entry<String, JsonElement> entry : jobj.entrySet()) {
        prim = entry.getValue().getAsJsonPrimitive();
        if (prim.isBoolean()) {
            field = new Field(entry.getKey(), DataType.BOOLEAN);
            result.addField(field);
            result.setBooleanValue(field.getName(), prim.getAsBoolean());
        } else if (prim.isNumber()) {
            field = new Field(entry.getKey(), DataType.NUMERIC);
            result.addField(field);
            result.setNumericValue(field.getName(), prim.getAsNumber().doubleValue());
        } else {
            field = new Field(entry.getKey(), DataType.STRING);
            result.addField(field);
            result.setStringValue(field.getName(), prim.getAsString());
        }
    }

    return result;
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

/**
 * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed.
 *//* www.j  a va2  s . c o  m*/
public static NBTBase parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        for (int id = 0; id < NBTTypes.length; id++) {
            if (string.startsWith(NBTTypes[id] + ":")) {
                String value = string.replace(NBTTypes[id] + ":", "");
                value = RandomRegistry.solveRandom(id, value);
                switch (id) {
                // 0 = END
                case BYTE:
                    return new NBTTagByte(Byte.parseByte(value));
                case SHORT:
                    return new NBTTagShort(Short.parseShort(value));
                case INT:
                    return new NBTTagInt(Integer.parseInt(value));
                case LONG:
                    return new NBTTagLong(Long.parseLong(value));
                case FLOAT:
                    return new NBTTagFloat(Float.parseFloat(value));
                case DOUBLE:
                    return new NBTTagDouble(Double.parseDouble(value));
                case BYTE_ARRAY:
                    return parseJSONByteArray(value);
                case STRING:
                    return new NBTTagString(value);
                // 9 = LIST != JsonPrimitive
                // 10 = COMPOUND != JsonPrimitive
                case INT_ARRAY:
                    return parseJSONIntArray(value);
                }
            }
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new NBTTagString(string);
    if (element.isBoolean())
        return new NBTTagByte((byte) (element.getAsBoolean() ? 1 : 0));

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new NBTTagByte(n.byteValue());
    if (n instanceof Short)
        return new NBTTagShort(n.shortValue());
    if (n instanceof Integer)
        return new NBTTagInt(n.intValue());
    if (n instanceof Long)
        return new NBTTagLong(n.longValue());
    if (n instanceof Float)
        return new NBTTagFloat(n.floatValue());
    if (n instanceof Double)
        return new NBTTagDouble(n.doubleValue());

    throw new NumberFormatException(element.toString() + " is was not able to be parsed.");
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

From source file:ch.cern.db.flume.sink.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java

License:GNU General Public License

private void appendBody(XContentBuilder builder, Event event) throws IOException {
    JsonParser parser = new JsonParser();

    JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject();

    for (Entry<String, JsonElement> property : json.entrySet()) {

        if (property.getValue().isJsonNull()) {
            builder.nullField(property.getKey());

            continue;
        }/*from   ww w .j av a 2 s  . c  o m*/

        if (!property.getValue().isJsonPrimitive()) {
            builder.field(property.getKey(), property.getValue());

            continue;
        }

        JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue();

        if (primitiveValue.isBoolean())
            builder.field(property.getKey(), primitiveValue.getAsBoolean());
        else if (primitiveValue.isNumber())
            if (primitiveValue.getAsString().indexOf('.') != -1)
                builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue());
            else
                builder.field(property.getKey(), primitiveValue.getAsNumber().longValue());
        else if (primitiveValue.isString())
            builder.field(property.getKey(), primitiveValue.getAsString());
    }
}

From source file:com.balajeetm.mystique.core.module.GsonSerialiser.java

License:Open Source License

@Override
public void serialize(JsonElement value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (jsonLever.isNull(value)) {
        gen.writeNull();/*from   w  ww. java 2  s  .c o m*/
    } else if (jsonLever.isObject(value)) {
        gen.writeStartObject();
        JsonObject jsonObject = value.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            gen.writeFieldName(entry.getKey());
            serialize(entry.getValue(), gen, provider);
        }
        gen.writeEndObject();
    } else if (jsonLever.isArray(value)) {
        gen.writeStartArray();
        JsonArray jsonArray = value.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            serialize(jsonElement, gen, provider);
        }
        gen.writeEndArray();
    } else if (jsonLever.isPrimitive(value)) {
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            gen.writeBoolean(jsonPrimitive.getAsBoolean());
        }
        if (jsonPrimitive.isNumber()) {
            Number nnode = jsonPrimitive.getAsNumber();
            if (nnode instanceof LazilyParsedNumber) {
                gen.writeNumber(nnode.toString());
            } else if (nnode instanceof Integer) {
                gen.writeNumber(nnode.intValue());
            } else if (nnode instanceof Short) {
                gen.writeNumber(nnode.shortValue());
            } else if (nnode instanceof BigInteger || nnode instanceof Long) {
                gen.writeNumber(nnode.longValue());
            } else if (nnode instanceof Float) {
                gen.writeNumber(nnode.floatValue());
            } else if (nnode instanceof Double || nnode instanceof BigDecimal) {
                gen.writeNumber(nnode.doubleValue());
            }
        }
        if (jsonPrimitive.isString()) {
            gen.writeString(jsonPrimitive.getAsString());
        }
    }
}

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }/*from   w w w  . jav  a  2 s  .c  o  m*/
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        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
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.canoo.dolphin.impl.codec.ValueEncoder.java

License:Apache License

static Object decodeValue(JsonElement jsonElement) {
    if (jsonElement == null || jsonElement.isJsonNull()) {
        return null;
    }//from  w ww.j av a 2  s.  co  m
    if (!jsonElement.isJsonPrimitive()) {
        throw new JsonParseException("Illegal JSON detected");
    }
    final JsonPrimitive value = (JsonPrimitive) jsonElement;

    if (value.isString()) {
        return value.getAsString();
    } else if (value.isBoolean()) {
        return value.getAsBoolean();
    } else if (value.isNumber()) {
        return value.getAsNumber();
    }
    throw new JsonParseException("Currently only String, Boolean, or Number are allowed as primitives");
}

From source file:com.facebook.buck.json.RawParser.java

License:Apache License

/**
 * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>.
 *///from   ww w .ja  v  a2 s.  co  m
@Nullable
@VisibleForTesting
static Object toRawTypes(JsonElement json) {
    // Cases are ordered from most common to least common.
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return interner.intern(primitive.getAsString());
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            Number number = primitive.getAsNumber();
            // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber.
            if (number.longValue() == number.doubleValue()) {
                return number.longValue();
            } else {
                return number;
            }
        } else {
            throw new IllegalStateException("Unknown primitive type: " + primitive);
        }
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> out = Lists.newArrayListWithCapacity(array.size());
        for (JsonElement item : array) {
            out.add(toRawTypes(item));
        }
        return out;
    } else if (json.isJsonObject()) {
        Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size());
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this
            // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError,
            // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings.
            // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the
            // OOM from happening.
            out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue()));
        }
        return out;
    } else if (json.isJsonNull()) {
        return null;
    } else {
        throw new IllegalStateException("Unknown type: " + json);
    }
}

From source file:com.flipkart.polyguice.config.JsonConfiguration.java

License:Apache License

private void flatten(String prefix, JsonElement element) {
    if (element.isJsonPrimitive()) {
        JsonPrimitive jsonPrim = element.getAsJsonPrimitive();
        if (jsonPrim.isBoolean()) {
            configTab.put(prefix, jsonPrim.getAsBoolean());
        } else if (jsonPrim.isNumber()) {
            configTab.put(prefix, jsonPrim.getAsNumber());
        } else if (jsonPrim.isString()) {
            configTab.put(prefix, jsonPrim.getAsString());
        }//  w ww  .j av a 2s . c  o m
    } else if (element.isJsonObject()) {
        JsonObject jsonObj = element.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
            String prefix1 = ((prefix != null) ? prefix + "." : "") + entry.getKey();
            flatten(prefix1, entry.getValue());
        }
    }
}

From source file:com.headswilllol.mineflat.world.SaveManager.java

License:Open Source License

public static Chunk loadChunk(Level level, int chunk) {
    JsonObject jChunk = level.getWorld().getJson().getAsJsonObject("levels")
            .getAsJsonObject(Integer.toString(level.getIndex())).getAsJsonObject("chunks")
            .getAsJsonObject(Integer.toString(chunk));
    if (jChunk != null) {
        System.out.println("Loading chunk " + chunk);
        Biome biome = Biome.getById(jChunk.get("biome").toString());
        Chunk c = new Chunk(level, chunk, biome);
        for (JsonElement blockObj : jChunk.getAsJsonArray("blocks")) {
            JsonObject block = blockObj.getAsJsonObject();
            Material type = Material.valueOf(block.get("type").getAsString());
            if (type == null)
                type = Material.AIR;//from  ww w.j a  v  a 2s .  co m
            int data = block.get("data") != null ? block.get("data").getAsInt() : 0;
            Block b = new Block(type, data,
                    new Location(level, Chunk.getWorldXFromChunkIndex(chunk, block.get("x").getAsLong()),
                            block.get("y").getAsLong()));
            JsonObject meta = (JsonObject) block.get("metadata");
            for (Map.Entry<String, JsonElement> e : meta.entrySet()) {
                JsonPrimitive prim = meta.get(e.getKey()).getAsJsonPrimitive();
                Object value;
                if (prim.isBoolean())
                    value = prim.getAsBoolean();
                else if (prim.isNumber())
                    value = prim.getAsNumber();
                else if (prim.isString())
                    value = prim.getAsString();
                else
                    value = prim.getAsCharacter();
                b.setMetadata(e.getKey(), value);
            }
            b.addToWorld();
        }
        for (Object entityObj : jChunk.get("entities").getAsJsonArray()) {
            JsonObject entity = (JsonObject) entityObj;
            EntityType type = EntityType.valueOf(entity.get("type").getAsString());
            float x = Chunk.getWorldXFromChunkIndex(c.getIndex(),
                    Float.valueOf(Double.toString(entity.get("x").getAsDouble())));
            float y = Float.valueOf(Double.toString(entity.get("y").getAsDouble()));
            float w = Float.valueOf(Double.toString(entity.get("w").getAsDouble()));
            float h = Float.valueOf(Double.toString(entity.get("h").getAsDouble()));
            Entity e;
            if (entity.has("living")) {
                if (entity.has("mob")) {
                    switch (type) {
                    case GHOST:
                        e = new Ghost(new Location(level, x, y));
                        break;
                    case SNAIL:
                        e = new Snail(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                    ((Mob) e).setPlannedWalkDistance(entity.get("pwd").getAsFloat());
                    ((Mob) e).setActualWalkDistance(entity.get("awd").getAsFloat());
                    ((Mob) e).setLastX(entity.get("lx").getAsFloat());
                } else {
                    switch (type) {
                    case PLAYER:
                        e = new Player(new Location(level, x, y));
                        break;
                    case HUMAN:
                        e = new Human(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                }
                ((Living) e).setFacingDirection(Direction.valueOf(entity.get("fd").getAsString()));
                ((Living) e).setJumping(entity.get("j").getAsBoolean());
            } else
                e = new Entity(type, new Location(level, x, y), w, h);
            e.getVelocity().setX(Float.valueOf(Double.toString(entity.get("xv").getAsDouble())));
            e.getVelocity().setY(Float.valueOf(Double.toString(entity.get("yv").getAsDouble())));
            level.addEntity(e);
            if (type == EntityType.PLAYER)
                Main.player = (Player) e;
        }
        c.updateLight();
        Chunk left = c.getLevel().getChunk(c.getIndex() == 1 ? -1 : c.getIndex() - 1);
        Chunk right = c.getLevel().getChunk(c.getIndex() == -1 ? 1 : c.getIndex() + 1);
        if (left != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                left.getBlock(c.getLevel().getWorld().getChunkLength() - 1, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), left.getIndex());
            }
        }
        if (right != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                right.getBlock(0, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), right.getIndex());
            }
        }
        System.gc(); //TODO: temporary fix until I have the motivation to find the memory leak
        return c;
    }
    return null;
}