Example usage for com.google.gson JsonPrimitive isString

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

Introduction

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

Prototype

public boolean isString() 

Source Link

Document

Check whether this primitive contains a String value.

Usage

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSource.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a
 * {@link DataContainer}./*www. j  av  a2s .c o m*/
 * 
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.writeBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.writeString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.writeNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.writeContainer(key, toContainer(element));
            }
        }
    }

    return container;

}

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSourceReader.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a {@link DataContainer}.
 * /*from   w  ww.  ja  v a 2  s.  c o m*/
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.setBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.setString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.setNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.setContainer(key, toContainer(element));
            }
        }
    }

    return container;

}

From source file:cosmos.records.JsonRecords.java

License:Apache License

/**
 * Parses a {@link JsonObject{ into a MapRecord. A duplicate key in the JsonObject will
 * overwrite the previous key./*w  w  w  .  j a v a 2  s  .  com*/
 * @param map The JsonObject being parsed
 * @param generator Construct to generate a docId for this {@link MapRecord}
 * @return A MapRecord built from the {@link JsonObject}
 */
protected static MapRecord asMapRecord(JsonObject map, DocIdGenerator generator) {
    Map<Column, RecordValue<?>> data = Maps.newHashMap();
    for (Entry<String, JsonElement> entry : map.entrySet()) {
        final Column key = Column.create(entry.getKey());
        final JsonElement value = entry.getValue();

        if (value.isJsonNull()) {
            data.put(key, null);
        } else if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) value;

            // Numbers
            if (primitive.isNumber()) {
                NumberRecordValue<?> v;

                double d = primitive.getAsDouble();
                if ((int) d == d) {
                    v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                } else if ((long) d == d) {
                    v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                } else {
                    v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                }

                data.put(key, v);

            } else if (primitive.isString()) {
                // String
                data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

            } else if (primitive.isBoolean()) {
                // Boolean
                data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

            } else if (primitive.isJsonNull()) {
                // Is this redundant?
                data.put(key, null);
            } else {
                throw new RuntimeException("Unhandled primitive: " + primitive);
            }
        } else {
            throw new RuntimeException("Expected a String, Number or Boolean");
        }
    }

    return new MapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS);
}

From source file:cosmos.records.JsonRecords.java

License:Apache License

/**
 * Builds a {@link MultimapRecord} from the provided {@link JsonObject} using a docid
 * from the {@link DocIdGenerator}. This method will support lists of values for a key
 * in the {@link JsonObject} but will fail on values which are {@link JsonObject}s and 
 * values which have nested {@link JsonArray}s. 
 * @param map The {@link JsonObject} to build this {@link MultimapRecord} from
 * @param generator {@link DocIdGenerator} to construct a docid for this {@link MultimapRecord}
 * @return A {@link MultimapRecord} built from the provided arguments.
 *///  w  w  w. j a  va2 s .  co  m
protected static MultimapRecord asMultimapRecord(JsonObject map, DocIdGenerator generator) {
    Multimap<Column, RecordValue<?>> data = HashMultimap.create();
    for (Entry<String, JsonElement> entry : map.entrySet()) {
        final Column key = Column.create(entry.getKey());
        final JsonElement value = entry.getValue();

        if (value.isJsonNull()) {
            data.put(key, null);
        } else if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) value;

            // Numbers
            if (primitive.isNumber()) {
                NumberRecordValue<?> v;

                double d = primitive.getAsDouble();
                if ((int) d == d) {
                    v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                } else if ((long) d == d) {
                    v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                } else {
                    v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                }

                data.put(key, v);

            } else if (primitive.isString()) {
                // String
                data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

            } else if (primitive.isBoolean()) {
                // Boolean
                data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

            } else if (primitive.isJsonNull()) {
                // Is this redundant?
                data.put(key, null);
            } else {
                throw new RuntimeException("Unhandled primitive: " + primitive);
            }
        } else if (value.isJsonArray()) {

            // Multimaps should handle the multiple values, not fail
            JsonArray values = value.getAsJsonArray();
            for (JsonElement element : values) {
                if (element.isJsonNull()) {
                    data.put(key, null);
                } else if (element.isJsonPrimitive()) {

                    JsonPrimitive primitive = (JsonPrimitive) element;

                    // Numbers
                    if (primitive.isNumber()) {
                        NumberRecordValue<?> v;

                        double d = primitive.getAsDouble();
                        if ((int) d == d) {
                            v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                        } else if ((long) d == d) {
                            v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                        } else {
                            v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                        }

                        data.put(key, v);

                    } else if (primitive.isString()) {
                        // String
                        data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

                    } else if (primitive.isBoolean()) {
                        // Boolean
                        data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

                    } else if (primitive.isJsonNull()) {
                        // Is this redundant?
                        data.put(key, null);
                    } else {
                        throw new RuntimeException("Unhandled Json primitive: " + primitive);
                    }
                } else {
                    throw new RuntimeException("Expected a Json primitive");
                }
            }

        } else {
            throw new RuntimeException("Expected a String, Number or Boolean");
        }
    }

    return new MultimapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS);

}

From source file:Days.Day12.java

public int parseObject(JsonObject object) {
    boolean hasRed = false;
    int totaal = 0;
    for (Entry<String, JsonElement> entry : object.entrySet()) {
        if (entry.getKey().equalsIgnoreCase("red")) {
            hasRed = true;//from   www  .  j  a v  a  2 s  .c o m
            break;
        } else {
            try {
                totaal += Integer.parseInt(entry.getKey());
            } catch (NumberFormatException e) {

            }
        }
        if (entry.getValue().isJsonPrimitive()) {
            JsonPrimitive value = entry.getValue().getAsJsonPrimitive();
            if (value.isString() && value.getAsString().equalsIgnoreCase("red")) {
                hasRed = true;
                break;
            }
        }
    }
    if (!hasRed) {
        for (Entry<String, JsonElement> entry : object.entrySet()) {
            totaal += parseElement(entry.getValue());
        }
    }
    return totaal;
}

From source file:de.azapps.mirakel.model.task.TaskDeserializer.java

License:Open Source License

private static void handleAdditionalEntries(final Task t, final String key, final JsonElement val) {
    if (val.isJsonPrimitive()) {
        final JsonPrimitive p = (JsonPrimitive) val;
        if (p.isBoolean()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsBoolean()));
        } else if (p.isNumber()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsInt()));
        } else if (p.isJsonNull()) {
            t.addAdditionalEntry(key, "null");
        } else if (p.isString()) {
            t.addAdditionalEntry(key, '"' + val.getAsString() + '"');
        } else {/* w  w w. j a va 2  s  .com*/
            Log.w(TAG, "unknown json-type");
        }
    } else if (val.isJsonArray()) {
        final JsonArray a = (JsonArray) val;
        StringBuilder s = new StringBuilder("[");
        boolean first = true;
        for (final JsonElement e : a) {
            if (e.isJsonPrimitive()) {
                final JsonPrimitive p = (JsonPrimitive) e;
                final String add;
                if (p.isBoolean()) {
                    add = String.valueOf(p.getAsBoolean());
                } else if (p.isNumber()) {
                    add = String.valueOf(p.getAsInt());
                } else if (p.isString()) {
                    add = '"' + p.getAsString() + '"';
                } else if (p.isJsonNull()) {
                    add = "null";
                } else {
                    Log.w(TAG, "unknown json-type");
                    break;
                }
                s.append(first ? "" : ",").append(add);
                first = false;
            } else {
                Log.w(TAG, "unknown json-type");
            }
        }
        t.addAdditionalEntry(key, s + "]");
    } else {
        Log.w(TAG, "unknown json-type");
    }
}

From source file:de.csdev.ebus.cfg.std.EBusValueJsonDeserializer.java

License:Open Source License

@Override
public List<EBusValueDTO> deserialize(JsonElement jElement, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonArray asJsonArray = jElement.getAsJsonArray();
    ArrayList<EBusValueDTO> result = new ArrayList<EBusValueDTO>();

    ArrayList<String> fields = new ArrayList<String>();
    for (Field field : EBusValueDTO.class.getDeclaredFields()) {
        SerializedName annotation = field.getAnnotation(SerializedName.class);

        if (annotation != null) {
            fields.add(annotation.value());

        } else {//from  w  w  w.jav  a 2s  . c o  m
            fields.add(field.getName());
        }
    }

    for (JsonElement jsonElement : asJsonArray) {
        JsonObject jObject = jsonElement.getAsJsonObject();
        EBusValueDTO valueDTO = context.deserialize(jObject, EBusValueDTO.class);

        for (Entry<String, JsonElement> entry : jObject.entrySet()) {
            if (!fields.contains(entry.getKey())) {

                if (entry.getValue().isJsonPrimitive()) {
                    JsonPrimitive primitive = (JsonPrimitive) entry.getValue();

                    if (primitive.isNumber()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsBigDecimal());

                    } else if (primitive.isBoolean()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsBoolean());

                    } else if (primitive.isString()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsString());
                    }

                } else {
                    valueDTO.setProperty(entry.getKey(), entry.getValue().getAsString());

                }

            }
        }

        result.add(valueDTO);
    }

    return result;
}

From source file:de.sub.goobi.helper.HelperSchritte.java

License:Open Source License

private void replaceJsonElement(JsonElement jel, VariableReplacer replacer) {
    if (jel.isJsonObject()) {
        JsonObject obj = jel.getAsJsonObject();
        for (Entry<String, JsonElement> objEntry : obj.entrySet()) {
            if (objEntry.getValue().isJsonPrimitive()) {
                JsonPrimitive jPrim = objEntry.getValue().getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    obj.addProperty(objEntry.getKey(), newVal);
                }/*from www.  jav a  2 s .  c o  m*/
            } else {
                replaceJsonElement(objEntry.getValue(), replacer);
            }
        }
    } else if (jel.isJsonArray()) {
        JsonArray jArr = jel.getAsJsonArray();
        for (int i = 0; i < jArr.size(); i++) {
            JsonElement innerJel = jArr.get(i);
            if (innerJel.isJsonPrimitive()) {
                JsonPrimitive jPrim = innerJel.getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    jArr.set(i, new JsonPrimitive(newVal));
                }
            } else {
                replaceJsonElement(innerJel, replacer);
            }
        }
    }

}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

private static void addConstraints(Template tpl, String json) {
    JsonElement el = new JsonParser().parse(json);
    for (JsonElement tel : el.getAsJsonArray()) {
        JsonObject triple = tel.getAsJsonObject();
        String subj = triple.getAsJsonObject("subject").get("id").getAsString();
        String pred = triple.getAsJsonObject("predicate").get("id").getAsString();
        JsonObject objitem = triple.getAsJsonObject("object");
        if (objitem.get("value") != null && objitem.get("isLiteral").getAsBoolean()) {
            JsonPrimitive obj = objitem.get("value").getAsJsonPrimitive();
            String objtype = objitem.get("type") != null ? objitem.get("type").getAsString() : null;
            tpl.getConstraintEngine().createNewDataConstraint(subj, pred,
                    obj.isString() ? obj.getAsString() : obj.toString(), objtype);
        } else {//from www  .j  a v a 2 s  .  c  o m
            String obj = objitem.get("id").getAsString();
            tpl.getConstraintEngine().createNewConstraint(subj, pred, obj);
        }
    }
}

From source file:fr.zcraft.MultipleInventories.snaphots.ItemStackSnapshot.java

License:Open Source License

/**
 * From a JSON element, constructs a data structure representing
 * the same structure (recursively) using native types.
 *
 * <p>We had to re-implement this to ensure the generated structure to have the
 * right data type (instead of all numbers being doubles) and precision.</p>
 *
 * @param element The json element to be decoded.
 * @return A native data structure (either a {@link Map Map&lt;String, Object&gt;},
 * a {@link List List&lt;Object&gt;}, or a native type) representing the same
 * structure (recursively).//from w w  w  .j a  v  a2  s .  co m
 *
 * @see #jsonToNative(JsonObject) Converts a json object to an explicit {@link Map}.
 * The JavaDoc also contains explainations on why this is needed.
 */
private static Object jsonToNative(final JsonElement element) {
    if (element.isJsonObject()) {
        return jsonToNative(element.getAsJsonObject());
    } else if (element.isJsonArray()) {
        final List<Object> list = new ArrayList<>();

        element.getAsJsonArray().forEach(listElement -> {
            final Object nativeValue = jsonToNative(listElement);

            if (nativeValue != null) {
                list.add(nativeValue);
            }
        });

        return list;
    } else if (element.isJsonPrimitive()) {
        final JsonPrimitive primitive = element.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else /* it's a number we yet have to find the type. */
        {
            final BigDecimal number = primitive.getAsBigDecimal();

            try {
                return number.byteValueExact();
            } catch (final ArithmeticException e1) {
                try {
                    return number.shortValueExact();
                } catch (final ArithmeticException e2) {
                    try {
                        return number.intValueExact();
                    } catch (final ArithmeticException e3) {
                        try {
                            return number.longValueExact();
                        } catch (final ArithmeticException e4) {
                            try {
                                return number.doubleValue();
                            } catch (final ArithmeticException | NumberFormatException e5) {
                                return number;
                            }
                        }
                    }
                }
            }
        }
    }

    // Else the element is null.
    return null;
}